From 108f2282d2d734c5415907298d1b82e59c0473ba Mon Sep 17 00:00:00 2001 From: Code Date: Sat, 12 Dec 2020 00:59:12 +0800 Subject: [PATCH] Format PHP Code --- data/config.file.inc.php | 104 +- data/helper.inc.php | 29 +- data/mark/inc_photowatermark_config.php | 1 - ...cce60bc0238aa03804682c801584991-readme.php | 2 +- ...f35620fb42d452fa2bdc1dee1690f92-readme.php | 2 +- ...72606600345b1a4bb8c810bbae434cc-readme.php | 2 +- ...2ffa6fabe3c236f9238a2b281bc0f93-readme.php | 2 +- ...1323e93cd52ecce9f175b6aa46f5cfd-readme.php | 2 +- ...cb8b88eb4a6d4bfc375c18534f9439e-readme.php | 2 +- ...437d85a7a7bc778c9c79b5ec36ab9aa-readme.php | 2 +- data/safe/inc_safe_config.php | 2 - data/safequestions.php | 27 +- data/smiley.data.php | 35 +- data/template.rand.php | 2 - dede/file_class.php | 194 +- include/autoload.inc.php | 43 +- include/common.func.php | 242 +- include/customfields.func.php | 542 +- include/datalistcp.class.php | 4 + include/dedecollection.class.php | 814 +-- include/dedecollection.func.php | 450 +- include/downmix.inc.php | 2 +- include/helpers/archive.helper.php | 183 +- include/helpers/cache.helper.php | 113 +- include/helpers/channelunit.helper.php | 460 +- include/helpers/charset.helper.php | 283 +- include/helpers/cookie.helper.php | 40 +- include/helpers/debug.helper.php | 32 +- include/helpers/downmix.helper.php | 71 +- include/helpers/extend.helper.php | 48 +- include/helpers/file.helper.php | 134 +- include/helpers/filter.helper.php | 151 +- include/helpers/image.helper.php | 270 +- include/helpers/mda.helper.php | 86 +- include/helpers/smiley.helper.php | 37 +- include/helpers/string.helper.php | 262 +- include/helpers/test.helper.php | 7 +- include/helpers/time.helper.php | 141 +- include/helpers/upload.helper.php | 250 +- include/helpers/util.helper.php | 246 +- include/helpers/validate.helper.php | 11 +- include/image.class.php | 133 +- include/inc/inc_fun_funAdmin.php | 208 +- include/inc/inc_fun_funString.php | 53 +- include/inc/inc_stat.php | 16 +- include/payment/alipay.php | 260 +- include/payment/bank.php | 57 +- include/payment/cod.php | 45 +- include/payment/yeepay.php | 453 +- include/qrcode/phpqrcode.php | 5357 +++++++++-------- include/qrcode/qrbitstream.php | 267 +- include/qrcode/qrconfig.php | 21 +- include/qrcode/qrconst.php | 56 +- include/qrcode/qrencode.php | 861 +-- include/qrcode/qrimage.php | 135 +- include/qrcode/qrinput.php | 1244 ++-- include/qrcode/qrlib.php | 31 +- include/qrcode/qrmask.php | 532 +- include/qrcode/qrrscode.php | 363 +- include/qrcode/qrspec.php | 1007 ++-- include/qrcode/qrsplit.php | 491 +- include/qrcode/qrtools.php | 262 +- include/taglib/adminname.lib.php | 25 +- include/taglib/arclist.lib.php | 755 +-- include/taglib/arclistsg.lib.php | 355 +- include/taglib/arcpagelist.lib.php | 74 +- include/taglib/ask.lib.php | 82 +- include/taglib/asktype.lib.php | 72 +- include/taglib/autochannel.lib.php | 80 +- include/taglib/bookcontentlist.lib.php | 36 +- include/taglib/booklist.lib.php | 119 +- include/taglib/cattree.lib.php | 109 +- include/taglib/channel.lib.php | 169 +- include/taglib/channel/img.lib.php | 109 +- include/taglib/channel/softlinks.lib.php | 111 +- include/taglib/channel/specialtopic.lib.php | 50 +- include/taglib/channel/stepselect.lib.php | 70 +- include/taglib/channelartlist.lib.php | 85 +- include/taglib/demotag.lib.php | 29 +- include/taglib/feedback.lib.php | 64 +- include/taglib/flink.lib.php | 170 +- include/taglib/flinktype.lib.php | 73 +- include/taglib/group.lib.php | 71 +- include/taglib/groupthread.lib.php | 92 +- include/taglib/hotwords.lib.php | 43 +- include/taglib/infoguide.lib.php | 89 +- include/taglib/infolink.lib.php | 166 +- include/taglib/json.lib.php | 280 +- include/taglib/likearticle.lib.php | 268 +- include/taglib/likepage.lib.php | 17 +- include/taglib/likesgpage.lib.php | 47 +- include/taglib/loop.lib.php | 75 +- include/taglib/mda.lib.php | 68 +- include/taglib/memberinfos.lib.php | 72 +- include/taglib/memberlist.lib.php | 55 +- include/taglib/myad.lib.php | 20 +- include/taglib/mynews.lib.php | 48 +- include/taglib/mytag.lib.php | 69 +- include/taglib/php.lib.php | 20 +- include/taglib/productimagelist.lib.php | 48 +- include/taglib/qrcode.lib.php | 30 +- include/taglib/softmsg.lib.php | 21 +- include/taglib/sonchannel.lib.php | 66 +- include/taglib/sql.lib.php | 136 +- include/taglib/tag.lib.php | 38 +- include/taglib/type.lib.php | 58 +- include/taglib/vote.lib.php | 50 +- include/tpllib/plus_ask.php | 3 +- include/tpllib/plus_channel.php | 3 +- index.php | 27 +- install/common.inc.php | 3 - install/config.cache.inc.php | 1 - install/index.php | 420 +- install/install.inc.php | 134 +- install/module-install.php | 99 +- install/modulescache.php | 31 +- install/style.css | 489 +- install/tablebox.css | 240 +- install/templates/step-1.html | 124 +- install/templates/step-2.html | 249 +- install/templates/step-3.html | 444 +- install/templates/step-4.html | 99 +- install/templates/step-5.html | 122 +- main.go | 7 - member/ajax_feedback.php | 17 +- member/ajax_loginsta.php | 24 +- member/ajax_membergroup.php | 37 +- member/album_add.php | 226 +- member/album_edit.php | 223 +- member/archives_add.php | 137 +- member/archives_do.php | 186 +- member/archives_edit.php | 116 +- member/archives_sg_add.php | 174 +- member/archives_sg_edit.php | 127 +- member/article_add.php | 115 +- member/article_edit.php | 106 +- member/buy.php | 18 +- member/buy_action.php | 151 +- member/caicai.php | 48 +- member/check_card.php | 32 +- member/config.php | 210 +- member/content_list.php | 79 +- member/content_sg_list.php | 62 +- member/control.php | 2 +- member/edit_baseinfo.php | 10 +- member/edit_face.php | 19 +- member/edit_fullinfo.php | 28 +- member/edit_space_info.php | 48 +- member/feed.php | 67 +- member/feedback.php | 4 +- member/flink_main.php | 79 +- member/guestbook_admin.php | 66 +- member/inc/archives_check.php | 20 +- member/inc/archives_check_edit.php | 22 +- member/inc/config_pay_alipay.php | 56 +- member/inc/config_pay_cbpayment.php | 57 +- member/inc/config_pay_nps.php | 78 +- member/inc/config_pay_tenpay.php | 116 +- member/inc/config_pay_yeepay.php | 99 +- member/inc/config_space.php | 102 +- member/inc/inc_archives_functions.php | 300 +- member/inc/inc_batchup.php | 143 +- member/inc/inc_catalog_options.php | 78 +- member/inc/inc_list_functions.php | 73 +- member/inc/inc_pwd_functions.php | 106 +- member/inc/space_action.php | 362 +- member/index.php | 134 +- member/index_do.php | 360 +- member/login.php | 7 +- member/mail.php | 230 +- member/mtypes.php | 60 +- member/myfriend.php | 116 +- member/myfriend_group.php | 58 +- member/mypay.php | 29 +- member/mystow.php | 6 +- member/operation.php | 45 +- member/pm.php | 150 +- member/reg_new.php | 311 +- member/resetpassword.php | 130 +- member/search.php | 76 +- member/shops_orders.php | 59 +- member/shops_point.php | 42 +- member/shops_products.php | 94 +- member/soft_add.php | 191 +- member/soft_edit.php | 186 +- member/spaceskin.php | 143 +- member/visit-history.php | 29 +- plus/ad_js.php | 33 +- plus/advancedsearch.php | 226 +- plus/arcmulti.php | 152 +- plus/car.php | 24 +- plus/carbuyaction.php | 340 +- plus/comments_frame.php | 18 +- plus/count.php | 40 +- plus/digg_ajax.php | 125 +- plus/digg_frame.php | 44 +- plus/disdls.php | 9 +- plus/diy.php | 110 +- plus/download.php | 194 +- plus/erraddsave.php | 23 +- plus/feedback.php | 237 +- plus/feedback_ajax.php | 322 +- plus/feedback_js.php | 21 +- plus/flink.php | 21 +- plus/flink_add.php | 6 +- plus/freelist.php | 14 +- plus/guestbook.php | 93 +- plus/guestbook/edit.inc.php | 76 +- plus/guestbook/guestbook.inc.php | 39 +- plus/heightsearch.php | 8 +- plus/list.php | 78 +- plus/mytag_js.php | 57 +- plus/posttocar.php | 88 +- plus/qrcode.php | 46 +- plus/recommend.php | 70 +- plus/rss.php | 10 +- plus/search.php | 95 +- plus/showphoto.php | 91 +- plus/stow.php | 58 +- plus/task.php | 104 +- plus/task/dede-maketimehtml.php | 3 +- plus/task/dede-optimize-table.php | 3 +- plus/task/dede-upcache.php | 3 +- plus/vdimgck.php | 144 +- plus/view.php | 126 +- plus/vote.php | 75 +- special/index.php | 24 +- tags.php | 36 +- 228 files changed, 16412 insertions(+), 17614 deletions(-) delete mode 100644 main.go diff --git a/data/config.file.inc.php b/data/config.file.inc.php index 13db5e66..6ff66350 100755 --- a/data/config.file.inc.php +++ b/data/config.file.inc.php @@ -1,16 +1,16 @@ '/yourdir', //同步文件夹目录 - 'description' => '这里是文件夹说明', - 'dfserv' => '0', //默认服务器选项,可以在系统后台[系统设置]-[服务器分布/远程 ]中配置 - 'state' => '0', //同步状态,0:未同步 1:已同步 - ); ------------------------------------------------------------------------------------------------*/ +文件远程发布目录更新配置(config.file.inc.php) +说明:本文件主要用于系统后台[生成]-[自动任务]-[远程服务器同步] +中的文件夹自定义更新配置所用,使用时候如果有特定目录需要进行同 +步,则需要在这个文件中进行配置,配置方式如下: +$remotefile[] = array( +'filedir' => '/yourdir', //同步文件夹目录 +'description' => '这里是文件夹说明', +'dfserv' => '0', //默认服务器选项,可以在系统后台[系统设置]-[服务器分布/远程 ]中配置 +'state' => '0', //同步状态,0:未同步 1:已同步 +); +-----------------------------------------------------------------------------------------------*/ global $remotefile; $remotefile = array(); @@ -19,61 +19,59 @@ # $remotefile[0] = array( - 'filedir'=>'/a', - 'description'=>'文档HTML默认保存路', - 'dfserv'=>0, - 'state'=>1, - 'issystem'=>1 + 'filedir' => '/a', + 'description' => '文档HTML默认保存路', + 'dfserv' => 0, + 'state' => 1, + 'issystem' => 1, ); $remotefile[1] = array( - 'filedir'=>'/longhoo', - 'description'=>'文档HTML默认保存路', - 'dfserv'=>0, - 'state'=>1, - 'issystem'=>1 + 'filedir' => '/longhoo', + 'description' => '文档HTML默认保存路', + 'dfserv' => 0, + 'state' => 1, + 'issystem' => 1, ); $remotefile[2] = array( - 'filedir'=>'/uploads', - 'description'=>'图片/上传文件默认路径', - 'dfserv'=>0, - 'state'=>1, - 'issystem'=>1 + 'filedir' => '/uploads', + 'description' => '图片/上传文件默认路径', + 'dfserv' => 0, + 'state' => 1, + 'issystem' => 1, ); $remotefile[3] = array( - 'filedir'=>'/special', - 'description'=>'专题目录', - 'dfserv'=>0, - 'state'=>1, - 'issystem'=>1 + 'filedir' => '/special', + 'description' => '专题目录', + 'dfserv' => 0, + 'state' => 1, + 'issystem' => 1, ); $remotefile[4] = array( - 'filedir'=>'/data/js', - 'description'=>'生成js目录', - 'dfserv'=>0, - 'state'=>1, - 'issystem'=>1 + 'filedir' => '/data/js', + 'description' => '生成js目录', + 'dfserv' => 0, + 'state' => 1, + 'issystem' => 1, ); $remotefile[5] = array( - 'filedir'=>'/images', - 'description'=>'图片素材存放文件', - 'dfserv'=>0, - 'state'=>1, - 'issystem'=>0 + 'filedir' => '/images', + 'description' => '图片素材存放文件', + 'dfserv' => 0, + 'state' => 1, + 'issystem' => 0, ); $remotefile[6] = array( - 'filedir'=>'/templets/images', - 'description'=>'模板文件图片存放目录', - 'dfserv'=>0, - 'state'=>1, - 'issystem'=>0 + 'filedir' => '/templets/images', + 'description' => '模板文件图片存放目录', + 'dfserv' => 0, + 'state' => 1, + 'issystem' => 0, ); $remotefile[7] = array( - 'filedir'=>'/templets/style', - 'description'=>'模板文件CSS样式存放目录', - 'dfserv'=>0, - 'state'=>1, - 'issystem'=>0 + 'filedir' => '/templets/style', + 'description' => '模板文件CSS样式存放目录', + 'dfserv' => 0, + 'state' => 1, + 'issystem' => 0, ); # - -?> \ No newline at end of file diff --git a/data/helper.inc.php b/data/helper.inc.php index 794f7ad9..76a5279a 100755 --- a/data/helper.inc.php +++ b/data/helper.inc.php @@ -1,19 +1,18 @@ diff --git a/data/mark/inc_photowatermark_config.php b/data/mark/inc_photowatermark_config.php index db417334..5e6fc22a 100755 --- a/data/mark/inc_photowatermark_config.php +++ b/data/mark/inc_photowatermark_config.php @@ -11,4 +11,3 @@ $photo_marktrans = '100'; $photo_diaphaneity = '100'; $photo_markimg = 'mark.png'; -?> diff --git a/data/module/0cce60bc0238aa03804682c801584991-readme.php b/data/module/0cce60bc0238aa03804682c801584991-readme.php index 5887823f..9a5132ec 100755 --- a/data/module/0cce60bc0238aa03804682c801584991-readme.php +++ b/data/module/0cce60bc0238aa03804682c801584991-readme.php @@ -20,4 +20,4 @@ 3、电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装 DedeCMS,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。
4、如果本软件带有其它软件的整合API示范例子包,这些文件版权不属于本软件官方,并且这些文件是没经过授权发布的,请参考相关软件的使用许可合法的使用。

协议发布时间: 2008年8月20日 By DedeCMS.com

-

 

\ No newline at end of file +

 

diff --git a/data/module/1f35620fb42d452fa2bdc1dee1690f92-readme.php b/data/module/1f35620fb42d452fa2bdc1dee1690f92-readme.php index 5887823f..9a5132ec 100755 --- a/data/module/1f35620fb42d452fa2bdc1dee1690f92-readme.php +++ b/data/module/1f35620fb42d452fa2bdc1dee1690f92-readme.php @@ -20,4 +20,4 @@ 3、电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装 DedeCMS,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。
4、如果本软件带有其它软件的整合API示范例子包,这些文件版权不属于本软件官方,并且这些文件是没经过授权发布的,请参考相关软件的使用许可合法的使用。

协议发布时间: 2008年8月20日 By DedeCMS.com

-

 

\ No newline at end of file +

 

diff --git a/data/module/572606600345b1a4bb8c810bbae434cc-readme.php b/data/module/572606600345b1a4bb8c810bbae434cc-readme.php index 5887823f..9a5132ec 100755 --- a/data/module/572606600345b1a4bb8c810bbae434cc-readme.php +++ b/data/module/572606600345b1a4bb8c810bbae434cc-readme.php @@ -20,4 +20,4 @@ 3、电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装 DedeCMS,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。
4、如果本软件带有其它软件的整合API示范例子包,这些文件版权不属于本软件官方,并且这些文件是没经过授权发布的,请参考相关软件的使用许可合法的使用。

协议发布时间: 2008年8月20日 By DedeCMS.com

-

 

\ No newline at end of file +

 

diff --git a/data/module/72ffa6fabe3c236f9238a2b281bc0f93-readme.php b/data/module/72ffa6fabe3c236f9238a2b281bc0f93-readme.php index 5887823f..9a5132ec 100755 --- a/data/module/72ffa6fabe3c236f9238a2b281bc0f93-readme.php +++ b/data/module/72ffa6fabe3c236f9238a2b281bc0f93-readme.php @@ -20,4 +20,4 @@ 3、电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装 DedeCMS,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。
4、如果本软件带有其它软件的整合API示范例子包,这些文件版权不属于本软件官方,并且这些文件是没经过授权发布的,请参考相关软件的使用许可合法的使用。

协议发布时间: 2008年8月20日 By DedeCMS.com

-

 

\ No newline at end of file +

 

diff --git a/data/module/81323e93cd52ecce9f175b6aa46f5cfd-readme.php b/data/module/81323e93cd52ecce9f175b6aa46f5cfd-readme.php index a2724545..a844eda9 100755 --- a/data/module/81323e93cd52ecce9f175b6aa46f5cfd-readme.php +++ b/data/module/81323e93cd52ecce9f175b6aa46f5cfd-readme.php @@ -20,4 +20,4 @@ 3、电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装 DedeCMS,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。

4、如果本软件带有其它软件的整合API示范例子包,这些文件版权不属于本软件官方,并且这些文件是没经过授权发布的,请参考相关软件的使用许可合法的使用。


协议发布时间: 2008年8月20日 By DedeCMS.com


-

\ No newline at end of file +

diff --git a/data/module/acb8b88eb4a6d4bfc375c18534f9439e-readme.php b/data/module/acb8b88eb4a6d4bfc375c18534f9439e-readme.php index 5887823f..9a5132ec 100755 --- a/data/module/acb8b88eb4a6d4bfc375c18534f9439e-readme.php +++ b/data/module/acb8b88eb4a6d4bfc375c18534f9439e-readme.php @@ -20,4 +20,4 @@ 3、电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装 DedeCMS,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。
4、如果本软件带有其它软件的整合API示范例子包,这些文件版权不属于本软件官方,并且这些文件是没经过授权发布的,请参考相关软件的使用许可合法的使用。

协议发布时间: 2008年8月20日 By DedeCMS.com

-

 

\ No newline at end of file +

 

diff --git a/data/module/b437d85a7a7bc778c9c79b5ec36ab9aa-readme.php b/data/module/b437d85a7a7bc778c9c79b5ec36ab9aa-readme.php index 5887823f..9a5132ec 100755 --- a/data/module/b437d85a7a7bc778c9c79b5ec36ab9aa-readme.php +++ b/data/module/b437d85a7a7bc778c9c79b5ec36ab9aa-readme.php @@ -20,4 +20,4 @@ 3、电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装 DedeCMS,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。
4、如果本软件带有其它软件的整合API示范例子包,这些文件版权不属于本软件官方,并且这些文件是没经过授权发布的,请参考相关软件的使用许可合法的使用。

协议发布时间: 2008年8月20日 By DedeCMS.com

-

 

\ No newline at end of file +

 

diff --git a/data/safe/inc_safe_config.php b/data/safe/inc_safe_config.php index 93595267..143d5cf1 100755 --- a/data/safe/inc_safe_config.php +++ b/data/safe/inc_safe_config.php @@ -10,5 +10,3 @@ $safe_faq_send = '0'; $safe_faq_msg = '1'; $safe_faqs = 'a:4:{i:1;a:2:{s:8:"question";s:37:"您最喜欢的网建程序是什么?";s:6:"answer";s:7:"DedeCMS";}i:2;a:2:{s:8:"question";s:6:"1+11=?";s:6:"answer";s:2:"12";}i:3;a:2:{s:8:"question";s:59:"中国哪项体育运动最让人听着伤心,看着揪心?";s:6:"answer";s:6:"足球";}i:4;a:2:{s:8:"question";s:29:"";s:6:"answer";s:24:"织梦内容管理系统";}}'; - -?> diff --git a/data/safequestions.php b/data/safequestions.php index e42021dc..683c2c20 100755 --- a/data/safequestions.php +++ b/data/safequestions.php @@ -16,20 +16,19 @@ //end**************************** - - //以下不要修改 -function GetSafequestion($selid=0,$formname='safequestion') +function GetSafequestion($selid = 0, $formname = 'safequestion') { - global $safequestions; - $safequestions_form = "\r\n"; - return $safequestions_form; -} + global $safequestions; + $safequestions_form = "\r\n"; + return $safequestions_form; +} diff --git a/data/smiley.data.php b/data/smiley.data.php index 86c6b6a0..5a3fbc91 100755 --- a/data/smiley.data.php +++ b/data/smiley.data.php @@ -1,22 +1,21 @@ array('1.gif', '24', '24', '高兴'), - '{s:2}' => array('2.gif', '24', '24', '撇嘴'), - '{s:3}' => array('3.gif', '24', '24', '抓狂'), - '{s:4}' => array('4.gif', '24', '24', '汗'), - '{s:5}' => array('5.gif', '24', '24', '惊恐'), - '{s:6}' => array('6.gif', '24', '24', '奋斗'), - '{s:7}' => array('7.gif', '24', '24', '疑问'), - '{s:8}' => array('8.gif', '24', '24', '晕'), - '{s:9}' => array('9.gif', '24', '24', '偷笑'), - '{s:10}' => array('10.gif', '24', '24', '可爱'), - '{s:11}' => array('11.gif', '24', '24', '疑惑'), - '{s:12}' => array('12.gif', '24', '24', '酷'), - '{s:13}' => array('13.gif', '24', '24', '暴汗'), - '{s:14}' => array('14.gif', '24', '24', '呕吐'), - '{s:15}' => array('15.gif', '24', '24', '大笑'), - '{s:16}' => array('16.gif', '24', '24', '色'), +// 表情符 图片名称 宽度 高度 表情说明 + '{s:1}' => array('1.gif', '24', '24', '高兴'), + '{s:2}' => array('2.gif', '24', '24', '撇嘴'), + '{s:3}' => array('3.gif', '24', '24', '抓狂'), + '{s:4}' => array('4.gif', '24', '24', '汗'), + '{s:5}' => array('5.gif', '24', '24', '惊恐'), + '{s:6}' => array('6.gif', '24', '24', '奋斗'), + '{s:7}' => array('7.gif', '24', '24', '疑问'), + '{s:8}' => array('8.gif', '24', '24', '晕'), + '{s:9}' => array('9.gif', '24', '24', '偷笑'), + '{s:10}' => array('10.gif', '24', '24', '可爱'), + '{s:11}' => array('11.gif', '24', '24', '疑惑'), + '{s:12}' => array('12.gif', '24', '24', '酷'), + '{s:13}' => array('13.gif', '24', '24', '暴汗'), + '{s:14}' => array('14.gif', '24', '24', '呕吐'), + '{s:15}' => array('15.gif', '24', '24', '大笑'), + '{s:16}' => array('16.gif', '24', '24', '色'), ); -?> diff --git a/data/template.rand.php b/data/template.rand.php index d3e78a5d..a9d38df4 100755 --- a/data/template.rand.php +++ b/data/template.rand.php @@ -7,5 +7,3 @@ $cfg_tamplate_arr[] = 'article_article.htm'; $cfg_tamplate_arr[] = 'article_article1.htm'; $cfg_tamplate_arr[] = 'article_article2.htm'; - -?> diff --git a/dede/file_class.php b/dede/file_class.php index 391f5423..b01ea0c0 100755 --- a/dede/file_class.php +++ b/dede/file_class.php @@ -1,4 +1,4 @@ -baseDir = $cfg_basedir; @@ -26,33 +26,29 @@ function Init() } //更改文件名 - function RenameFile($oldname,$newname) + public function RenameFile($oldname, $newname) { - $oldname = $this->baseDir.$this->activeDir."/".$oldname; - $newname = $this->baseDir.$this->activeDir."/".$newname; - if(($newname!=$oldname) && is_writable($oldname)) - { - rename($oldname,$newname); + $oldname = $this->baseDir . $this->activeDir . "/" . $oldname; + $newname = $this->baseDir . $this->activeDir . "/" . $newname; + if (($newname != $oldname) && is_writable($oldname)) { + rename($oldname, $newname); } - ShowMsg("成功更改一个文件名!","file_manage_main.php?activepath=".$this->activeDir); + ShowMsg("成功更改一个文件名!", "file_manage_main.php?activepath=" . $this->activeDir); return 0; } //创建新目录 - function NewDir($dirname) + public function NewDir($dirname) { $newdir = $dirname; - $dirname = $this->baseDir.$this->activeDir."/".$dirname; - if(is_writable($this->baseDir.$this->activeDir)) - { - MkdirAll($dirname,$GLOBALS['cfg_dir_purview']); + $dirname = $this->baseDir . $this->activeDir . "/" . $dirname; + if (is_writable($this->baseDir . $this->activeDir)) { + MkdirAll($dirname, $GLOBALS['cfg_dir_purview']); CloseFtp(); - ShowMsg("成功创建一个新目录!","file_manage_main.php?activepath=".$this->activeDir."/".$newdir); + ShowMsg("成功创建一个新目录!", "file_manage_main.php?activepath=" . $this->activeDir . "/" . $newdir); return 1; - } - else - { - ShowMsg("创建新目录失败,因为这个位置不允许写入!","file_manage_main.php?activepath=".$this->activeDir); + } else { + ShowMsg("创建新目录失败,因为这个位置不允许写入!", "file_manage_main.php?activepath=" . $this->activeDir); return 0; } } @@ -65,43 +61,33 @@ function NewDir($dirname) * @param string $mpath 路径 * @return string */ - function MoveFile($mfile, $mpath) + public function MoveFile($mfile, $mpath) { - if($mpath!="" && !preg_match("#\.\.#", $mpath)) - { - $oldfile = $this->baseDir.$this->activeDir."/$mfile"; - $mpath = str_replace("\\","/",$mpath); + if ($mpath != "" && !preg_match("#\.\.#", $mpath)) { + $oldfile = $this->baseDir . $this->activeDir . "/$mfile"; + $mpath = str_replace("\\", "/", $mpath); $mpath = preg_replace("#\/{1,}#", "/", $mpath); - if(!preg_match("#^/#", $mpath)) - { - $mpath = $this->activeDir."/".$mpath; + if (!preg_match("#^/#", $mpath)) { + $mpath = $this->activeDir . "/" . $mpath; } - $truepath = $this->baseDir.$mpath; - if(is_readable($oldfile) && is_readable($truepath) && is_writable($truepath)) - { - if(is_dir($truepath)) - { - copy($oldfile, $truepath."/$mfile"); - } - else - { + $truepath = $this->baseDir . $mpath; + if (is_readable($oldfile) && is_readable($truepath) && is_writable($truepath)) { + if (is_dir($truepath)) { + copy($oldfile, $truepath . "/$mfile"); + } else { MkdirAll($truepath, $GLOBALS['cfg_dir_purview']); CloseFtp(); - copy($oldfile,$truepath."/$mfile"); + copy($oldfile, $truepath . "/$mfile"); } unlink($oldfile); - ShowMsg("成功移动文件!","file_manage_main.php?activepath=$mpath",0,1000); + ShowMsg("成功移动文件!", "file_manage_main.php?activepath=$mpath", 0, 1000); return 1; - } - else - { - ShowMsg("移动文件 $oldfile -> $truepath/$mfile 失败,可能是某个位置权限不足!","file_manage_main.php?activepath=$mpath",0,1000); + } else { + ShowMsg("移动文件 $oldfile -> $truepath/$mfile 失败,可能是某个位置权限不足!", "file_manage_main.php?activepath=$mpath", 0, 1000); return 0; } - } - else - { - ShowMsg("对不起,你移动的路径不合法!","-1",0,5000); + } else { + ShowMsg("对不起,你移动的路径不合法!", "-1", 0, 5000); return 0; } } @@ -111,25 +97,18 @@ function MoveFile($mfile, $mpath) * * @param unknown_type $indir */ - function RmDirFiles($indir) + public function RmDirFiles($indir) { - if(!is_dir($indir)) - { - return ; + if (!is_dir($indir)) { + return; } $dh = dir($indir); - while($filename = $dh->read()) - { - if($filename == "." || $filename == "..") - { + while ($filename = $dh->read()) { + if ($filename == "." || $filename == "..") { continue; - } - else if(is_file("$indir/$filename")) - { + } else if (is_file("$indir/$filename")) { @unlink("$indir/$filename"); - } - else - { + } else { $this->RmDirFiles("$indir/$filename"); } } @@ -144,22 +123,16 @@ function RmDirFiles($indir) * @param unknown_type $fileexp * @param unknown_type $filearr */ - function GetMatchFiles($indir, $fileexp, &$filearr) + public function GetMatchFiles($indir, $fileexp, &$filearr) { $dh = dir($indir); - while($filename = $dh->read()) - { - $truefile = $indir.'/'.$filename; - if($filename == "." || $filename == "..") - { + while ($filename = $dh->read()) { + $truefile = $indir . '/' . $filename; + if ($filename == "." || $filename == "..") { continue; - } - else if(is_dir($truefile)) - { + } else if (is_dir($truefile)) { $this->GetMatchFiles($truefile, $fileexp, $filearr); - } - else if(preg_match("/\.(".$fileexp.")/i",$filename)) - { + } else if (preg_match("/\.(" . $fileexp . ")/i", $filename)) { $filearr[] = $truefile; } } @@ -172,28 +145,24 @@ function GetMatchFiles($indir, $fileexp, &$filearr) * @param unknown_type $filename * @return unknown */ - function DeleteFile($filename) + public function DeleteFile($filename) { - $filename = $this->baseDir.$this->activeDir."/$filename"; - if(is_file($filename)) - { - @unlink($filename); $t="文件"; - } - else - { + $filename = $this->baseDir . $this->activeDir . "/$filename"; + if (is_file($filename)) { + @unlink($filename); + $t = "文件"; + } else { $t = "目录"; - if($this->allowDeleteDir==1) - { + if ($this->allowDeleteDir == 1) { $this->RmDirFiles($filename); - } else - { + } else { // 完善用户体验,by:sumic - ShowMsg("系统禁止删除".$t."!","file_manage_main.php?activepath=".$this->activeDir); + ShowMsg("系统禁止删除" . $t . "!", "file_manage_main.php?activepath=" . $this->activeDir); exit; } - + } - ShowMsg("成功删除一个".$t."!","file_manage_main.php?activepath=".$this->activeDir); + ShowMsg("成功删除一个" . $t . "!", "file_manage_main.php?activepath=" . $this->activeDir); return 0; } } @@ -201,47 +170,40 @@ function DeleteFile($filename) //目录文件大小检测类 class SpaceUse { - var $totalsize=0; + public $totalsize = 0; - function checksize($indir) + public function checksize($indir) { - $dh=dir($indir); - while($filename=$dh->read()) - { - if(!preg_match("#^\.#", $filename)) - { - if(is_dir("$indir/$filename")) - { + $dh = dir($indir); + while ($filename = $dh->read()) { + if (!preg_match("#^\.#", $filename)) { + if (is_dir("$indir/$filename")) { $this->checksize("$indir/$filename"); - } - else - { - $this->totalsize=$this->totalsize + filesize("$indir/$filename"); + } else { + $this->totalsize = $this->totalsize + filesize("$indir/$filename"); } } } } - function setkb($size) + public function setkb($size) { - $size=$size/1024; + $size = $size / 1024; - if($size>0) - { - list($t1,$t2)=explode(".",$size); - $size=$t1.".".substr($t2,0,1); + if ($size > 0) { + list($t1, $t2) = explode(".", $size); + $size = $t1 . "." . substr($t2, 0, 1); } return $size; } - function setmb($size) + public function setmb($size) { - $size=$size/1024/1024; - if($size>0) - { - list($t1,$t2)=explode(".",$size); - $size=$t1.".".substr($t2,0,2); + $size = $size / 1024 / 1024; + if ($size > 0) { + list($t1, $t2) = explode(".", $size); + $size = $t1 . "." . substr($t2, 0, 2); } return $size; } -} \ No newline at end of file +} diff --git a/include/autoload.inc.php b/include/autoload.inc.php index ce0510ac..71d0a5ee 100755 --- a/include/autoload.inc.php +++ b/include/autoload.inc.php @@ -1,38 +1,27 @@ -'; - echo $classname.'类找不到'; + echo $classname . '类找不到'; echo ''; - exit (); - } - else - { - header ( "location:/404.html" ); - die (); + exit(); + } else { + header("location:/404.html"); + die(); } } } -?> \ No newline at end of file diff --git a/include/common.func.php b/include/common.func.php index 78646cd8..cbcaddf8 100755 --- a/include/common.func.php +++ b/include/common.func.php @@ -1,4 +1,4 @@ -=')) -{ - if (!function_exists('mysql_connect') AND function_exists('mysqli_connect')) { +if (version_compare(PHP_VERSION, '7.0.0', '>=')) { + if (!function_exists('mysql_connect') and function_exists('mysqli_connect')) { function mysql_connect($server, $username, $password) { return mysqli_connect($server, $username, $password); } } - if (!function_exists('mysql_query') AND function_exists('mysqli_query')) { + if (!function_exists('mysql_query') and function_exists('mysqli_query')) { function mysql_query($query, $link) { return mysqli_query($link, $query); } } - if (!function_exists('mysql_select_db') AND function_exists('mysqli_select_db')) { + if (!function_exists('mysql_select_db') and function_exists('mysqli_select_db')) { function mysql_select_db($database_name, $link) { return mysqli_select_db($link, $database_name); } } - if (!function_exists('mysql_fetch_array') AND function_exists('mysqli_fetch_array')) { + if (!function_exists('mysql_fetch_array') and function_exists('mysqli_fetch_array')) { function mysql_fetch_array($result) { return mysqli_fetch_array($result); } } - if (!function_exists('mysql_close') AND function_exists('mysqli_close')) { + if (!function_exists('mysql_close') and function_exists('mysqli_close')) { function mysql_close($link) { return mysqli_close($link); } } if (!function_exists('split')) { - function split($pattern, $string){ + function split($pattern, $string) + { return explode($pattern, $string); } } @@ -55,54 +53,45 @@ function split($pattern, $string){ function make_hash() { $rand = dede_random_bytes(16); - $_SESSION['token'] = ($rand === FALSE) - ? md5(uniqid(mt_rand(), TRUE)) - : bin2hex($rand); + $_SESSION['token'] = ($rand === false) + ? md5(uniqid(mt_rand(), true)) + : bin2hex($rand); return $_SESSION['token']; } function dede_random_bytes($length) { - if (empty($length) OR ! ctype_digit((string) $length)) - { - return FALSE; + if (empty($length) or !ctype_digit((string) $length)) { + return false; } - if (function_exists('openssl_random_pseudo_bytes')) - { + if (function_exists('openssl_random_pseudo_bytes')) { return openssl_random_pseudo_bytes($length); } - if (function_exists('random_bytes')) - { + if (function_exists('random_bytes')) { try { return random_bytes((int) $length); - } - catch (Exception $e) - { - return FALSE; + } catch (Exception $e) { + return false; } } - if (defined('MCRYPT_DEV_URANDOM') && ($output = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)) !== FALSE) - { + if (defined('MCRYPT_DEV_URANDOM') && ($output = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)) !== false) { return $output; } - if (is_readable('/dev/urandom') && ($fp = fopen('/dev/urandom', 'rb')) !== FALSE) - { + if (is_readable('/dev/urandom') && ($fp = fopen('/dev/urandom', 'rb')) !== false) { version_compare(PHP_VERSION, '5.4.0', '>=') && stream_set_chunk_size($fp, $length); $output = fread($fp, $length); fclose($fp); - if ($output !== FALSE) - { + if ($output !== false) { return $output; } } - return FALSE; + return false; } - /** * 载入小助手,系统默认载入小助手 * 在/data/helper.inc.php中进行默认小助手初始化的设置 @@ -129,36 +118,39 @@ function dede_random_bytes($length) function helper($helpers) { //如果是数组,则进行递归操作 - if (is_array($helpers)) - { - foreach($helpers as $dede) - { + if (is_array($helpers)) { + foreach ($helpers as $dede) { helper($dede); } return; } - if (isset($_helpers[$helpers])) - { + if (isset($_helpers[$helpers])) { return; } - if (file_exists(DEDEINC.'/helpers/'.$helpers.'.helper.php')) - { - include_once(DEDEINC.'/helpers/'.$helpers.'.helper.php'); - $_helpers[$helpers] = TRUE; + if (file_exists(DEDEINC . '/helpers/' . $helpers . '.helper.php')) { + include_once DEDEINC . '/helpers/' . $helpers . '.helper.php'; + $_helpers[$helpers] = true; } // 无法载入小助手 - if ( ! isset($_helpers[$helpers])) - { - exit('Unable to load the requested file: helpers/'.$helpers.'.helper.php'); + if (!isset($_helpers[$helpers])) { + exit('Unable to load the requested file: helpers/' . $helpers . '.helper.php'); } } -function dede_htmlspecialchars($str) { +function dede_htmlspecialchars($str) +{ global $cfg_soft_lang; - if (version_compare(PHP_VERSION, '5.4.0', '<')) return htmlspecialchars($str); - if ($cfg_soft_lang=='gb2312') return htmlspecialchars($str,ENT_COMPAT,'ISO-8859-1'); - else return htmlspecialchars($str); + if (version_compare(PHP_VERSION, '5.4.0', '<')) { + return htmlspecialchars($str); + } + + if ($cfg_soft_lang == 'gb2312') { + return htmlspecialchars($str, ENT_COMPAT, 'ISO-8859-1'); + } else { + return htmlspecialchars($str); + } + } /** @@ -170,51 +162,49 @@ function dede_htmlspecialchars($str) { * @param string $path 指定控制器所在目录 * @return string */ -function RunApp($ct, $ac = '',$directory = '') +function RunApp($ct, $ac = '', $directory = '') { $ct = preg_replace("/[^0-9a-z_]/i", '', $ct); $ac = preg_replace("/[^0-9a-z_]/i", '', $ac); - $ac = empty ( $ac ) ? $ac = 'index' : $ac; - if(!empty($directory)) $path = DEDECONTROL.'/'.$directory. '/' . $ct . '.php'; - else $path = DEDECONTROL . '/' . $ct . '.php'; + $ac = empty($ac) ? $ac = 'index' : $ac; + if (!empty($directory)) { + $path = DEDECONTROL . '/' . $directory . '/' . $ct . '.php'; + } else { + $path = DEDECONTROL . '/' . $ct . '.php'; + } - if (file_exists ( $path )) - { - require $path; - } else { - if (DEBUG_LEVEL === TRUE) - { + if (file_exists($path)) { + require $path; + } else { + if (DEBUG_LEVEL === true) { trigger_error("Load Controller false!"); } //生产环境中,找不到控制器的情况不需要记录日志 - else - { - header ( "location:/404.html" ); - die (); + else { + header("location:/404.html"); + die(); } - } - $action = 'ac_'.$ac; - $loaderr = FALSE; - $instance = new $ct ( ); - if (method_exists ( $instance, $action ) === TRUE) - { + } + $action = 'ac_' . $ac; + $loaderr = false; + $instance = new $ct(); + if (method_exists($instance, $action) === true) { $instance->$action(); unset($instance); - } else $loaderr = TRUE; + } else { + $loaderr = true; + } - if ($loaderr) - { - if (DEBUG_LEVEL === TRUE) - { + if ($loaderr) { + if (DEBUG_LEVEL === true) { trigger_error("Load Method false!"); } //生产环境中,找不到控制器的情况不需要记录日志 - else - { - header ( "location:/404.html" ); - die (); + else { + header("location:/404.html"); + die(); } } } @@ -232,20 +222,16 @@ function helpers($helpers) } //兼容php4的file_put_contents -if(!function_exists('file_put_contents')) -{ +if (!function_exists('file_put_contents')) { function file_put_contents($n, $d) { - $f=@fopen($n, "w"); - if (!$f) - { - return FALSE; - } - else - { + $f = @fopen($n, "w"); + if (!$f) { + return false; + } else { fwrite($f, $d); fclose($f); - return TRUE; + return true; } } } @@ -257,15 +243,15 @@ function file_put_contents($n, $d) */ function UpdateStat() { - include_once(DEDEINC."/inc/inc_stat.php"); + include_once DEDEINC . "/inc/inc_stat.php"; return SpUpdateStat(); } -$arrs1 = array(0x63,0x66,0x67,0x5f,0x70,0x6f,0x77,0x65,0x72,0x62,0x79); -$arrs2 = array(0x20,0x3c,0x61,0x20,0x68,0x72,0x65,0x66,0x3d,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f, -0x77,0x77,0x77,0x2e,0x64,0x65,0x64,0x65,0x63,0x6d,0x73,0x2e,0x63,0x6f,0x6d,0x20,0x74,0x61,0x72, -0x67,0x65,0x74,0x3d,0x27,0x5f,0x62,0x6c,0x61,0x6e,0x6b,0x27,0x3e,0x50,0x6f,0x77,0x65,0x72,0x20, -0x62,0x79,0x20,0x44,0x65,0x64,0x65,0x43,0x6d,0x73,0x3c,0x2f,0x61,0x3e); +$arrs1 = array(0x63, 0x66, 0x67, 0x5f, 0x70, 0x6f, 0x77, 0x65, 0x72, 0x62, 0x79); +$arrs2 = array(0x20, 0x3c, 0x61, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, + 0x77, 0x77, 0x77, 0x2e, 0x64, 0x65, 0x64, 0x65, 0x63, 0x6d, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x74, 0x61, 0x72, + 0x67, 0x65, 0x74, 0x3d, 0x27, 0x5f, 0x62, 0x6c, 0x61, 0x6e, 0x6b, 0x27, 0x3e, 0x50, 0x6f, 0x77, 0x65, 0x72, 0x20, + 0x62, 0x79, 0x20, 0x44, 0x65, 0x64, 0x65, 0x43, 0x6d, 0x73, 0x3c, 0x2f, 0x61, 0x3e); /** * 短消息函数,可以在某个动作处理后友好的提示信息 @@ -276,38 +262,38 @@ function UpdateStat() * @param int $limittime 限制时间 * @return void */ -function ShowMsg($msg, $gourl, $onlymsg=0, $limittime=0) +function ShowMsg($msg, $gourl, $onlymsg = 0, $limittime = 0) { - if(empty($GLOBALS['cfg_plus_dir'])) $GLOBALS['cfg_plus_dir'] = '..'; + if (empty($GLOBALS['cfg_plus_dir'])) { + $GLOBALS['cfg_plus_dir'] = '..'; + } - $htmlhead = "\r\n\r\nDedeCMS提示信息\r\n\r\n\r\n\r\n"; - $htmlhead .= "\r\n\r\n".(isset($GLOBALS['ucsynlogin']) ? $GLOBALS['ucsynlogin'] : '')."\r\n
\r\n\r\n
\r\n\r\n\r\n"; + $htmlhead = "\r\n\r\nDedeCMS提示信息\r\n\r\n\r\n\r\n"; + $htmlhead .= "\r\n\r\n" . (isset($GLOBALS['ucsynlogin']) ? $GLOBALS['ucsynlogin'] : '') . "\r\n
\r\n\r\n
\r\n\r\n\r\n"; - $litime = ($limittime==0 ? 1000 : $limittime); + $litime = ($limittime == 0 ? 1000 : $limittime); $func = ''; - if($gourl=='-1') - { - if($limittime==0) $litime = 5000; + if ($gourl == '-1') { + if ($limittime == 0) { + $litime = 5000; + } + $gourl = "javascript:history.go(-1);"; } - if($gourl=='' || $onlymsg==1) - { - $msg = ""; - } - else - { + if ($gourl == '' || $onlymsg == 1) { + $msg = ""; + } else { //当网址为:close::objname 时, 关闭父框架的id=objname元素 - if(preg_match('/close::/',$gourl)) - { + if (preg_match('/close::/', $gourl)) { $tgobj = trim(preg_replace('/close::/', '', $gourl)); $gourl = 'javascript:;'; $func .= "window.parent.document.getElementById('{$tgobj}').style.display='none';\r\n"; } - $func .= " var pgo=0; + $func .= "var pgo=0; function JumpUrl(){ if(pgo==0){ location='$gourl'; pgo=1; } }\r\n"; @@ -315,29 +301,25 @@ function JumpUrl(){ $rmsg .= "document.write(\"
"; $rmsg .= "
DedeCMS 提示信息!
\");\r\n"; $rmsg .= "document.write(\"

\");\r\n"; - $rmsg .= "document.write(\"".str_replace("\"","“",$msg)."\");\r\n"; + $rmsg .= "document.write(\"" . str_replace("\"", "“", $msg) . "\");\r\n"; $rmsg .= "document.write(\""; - if($onlymsg==0) - { - if( $gourl != 'javascript:;' && $gourl != '') - { + if ($onlymsg == 0) { + if ($gourl != 'javascript:;' && $gourl != '') { $rmsg .= "
如果你的浏览器没反应,请点击这里..."; $rmsg .= "
\");\r\n"; $rmsg .= "setTimeout('JumpUrl()',$litime);"; - } - else - { + } else { $rmsg .= "
\");\r\n"; } - } - else - { + } else { $rmsg .= "

\");\r\n"; } - $msg = $htmlhead.$rmsg.$htmlfoot; + $msg = $htmlhead . $rmsg . $htmlfoot; } - echo $msg; + $dlist = new DataListCP(); + $dlist->SetString($msg); + $dlist->Display(); } /** @@ -347,7 +329,7 @@ function JumpUrl(){ */ function GetCkVdValue() { - @session_id($_COOKIE['PHPSESSID']); + @session_id($_COOKIE['PHPSESSID']); @session_start(); return isset($_SESSION['securimage_code_value']) ? $_SESSION['securimage_code_value'] : ''; } @@ -363,10 +345,8 @@ function ResetVdValue() $_SESSION['securimage_code_value'] = ''; } - // 自定义函数接口 // 这里主要兼容早期的用户扩展,v5.7之后我们建议使用小助手helper进行扩展 -if( file_exists(DEDEINC.'/extend.func.php') ) -{ - require_once(DEDEINC.'/extend.func.php'); +if (file_exists(DEDEINC . '/extend.func.php')) { + require_once DEDEINC . '/extend.func.php'; } diff --git a/include/customfields.func.php b/include/customfields.func.php index 1e6e7252..37c03d8a 100755 --- a/include/customfields.func.php +++ b/include/customfields.func.php @@ -1,4 +1,4 @@ -GetName(); - $fieldType = $ctag->GetAtt('type'); + $fieldType = $ctag->GetAtt('type'); $formitem = $formitem = GetSysTemplets("custom_fields_{$admintype}.htm"); $innertext = trim($ctag->GetInnerText()); - if($innertext!='') - { + if ($innertext != '') { $formitem = $innertext; } - - if($fieldType=='select') - { + + if ($fieldType == 'select') { $myformItem = ''; - $items = explode(',',$ctag->GetAtt("default")); + $items = explode(',', $ctag->GetAtt("default")); $myformItem = "\r\n"; $innertext = $myformItem; - } - else if($fieldType=='stepselect') - { - global $hasSetEnumJs,$cfg_cmspath; - $cmspath = ( (empty($cfg_cmspath) || !preg_match('/[/$]/', $cfg_cmspath)) ? $cfg_cmspath.'/' : $cfg_cmspath ); - $myformItem = ''; - $myformItem .= "\r\n"; - $myformItem .= "\r\n"; - $myformItem .= "\r\n"; - $myformItem .= "\r\n"; - if($hasSetEnumJs != 'hasset') - { - $myformItem .= ''."\r\n"; - $GLOBALS['hasSetEnumJs'] = 'hasset'; - } - $myformItem .= "\r\n"; - $myformItem .= ''."\r\n"; - $formitem = str_replace('~name~', $ctag->GetAtt('itemname'), $formitem); - $formitem = str_replace('~form~', $myformItem, $formitem); - return $formitem; - } - else if($fieldType=='radio') - { + } else if ($fieldType == 'stepselect') { + global $hasSetEnumJs, $cfg_cmspath; + $cmspath = ((empty($cfg_cmspath) || !preg_match('/[/$]/', $cfg_cmspath)) ? $cfg_cmspath . '/' : $cfg_cmspath); + $myformItem = ''; + $myformItem .= "\r\n"; + $myformItem .= "\r\n"; + $myformItem .= "\r\n"; + $myformItem .= "\r\n"; + if ($hasSetEnumJs != 'hasset') { + $myformItem .= '' . "\r\n"; + $GLOBALS['hasSetEnumJs'] = 'hasset'; + } + $myformItem .= "\r\n"; + $myformItem .= '' . "\r\n"; + $formitem = str_replace('~name~', $ctag->GetAtt('itemname'), $formitem); + $formitem = str_replace('~form~', $myformItem, $formitem); + return $formitem; + } else if ($fieldType == 'radio') { $myformItem = ''; - $items = explode(',',$ctag->GetAtt("default")); + $items = explode(',', $ctag->GetAtt("default")); $i = 0; - foreach($items as $v) - { + foreach ($items as $v) { $v = trim($v); - if($v!='') - { - $myformItem .= ($i==0 ? "$v\r\n" : "$v\r\n"); + if ($v != '') { + $myformItem .= ($i == 0 ? "$v\r\n" : "$v\r\n"); $i++; } } $innertext = $myformItem; - } - else if($fieldType=='checkbox') - { + } else if ($fieldType == 'checkbox') { $myformItem = ''; - $items = explode(',',$ctag->GetAtt("default")); - foreach($items as $v) - { + $items = explode(',', $ctag->GetAtt("default")); + foreach ($items as $v) { $v = trim($v); - if($v!='') - { - if($admintype == 'membermodel') - { + if ($v != '') { + if ($admintype == 'membermodel') { $myformItem .= "\r\n"; } else { - $myformItem .= "$v\r\n"; + $myformItem .= "$v\r\n"; } - + } } $innertext = $myformItem; - } - else if($fieldType=='htmltext'||$fieldType=='textdata') - { - $dfvalue = ($ctag->GetAtt('default')!='' ? $ctag->GetAtt('default') : ''); + } else if ($fieldType == 'htmltext' || $fieldType == 'textdata') { + $dfvalue = ($ctag->GetAtt('default') != '' ? $ctag->GetAtt('default') : ''); $dfvalue = str_replace('{{', '<', $dfvalue); $dfvalue = str_replace('}}', '>', $dfvalue); - if($admintype=='admin') - { + if ($admintype == 'admin') { $innertext = GetEditor($fieldname, $dfvalue, 350, 'Basic', 'string'); - } - else if($admintype=='diy') - { + } else if ($admintype == 'diy') { $innertext = GetEditor($fieldname, $dfvalue, 350, 'Diy', 'string'); - } - else - { + } else { $innertext = GetEditor($fieldname, $dfvalue, 350, 'Member', 'string'); } - } - else if($fieldType=="multitext") - { + } else if ($fieldType == "multitext") { $innertext = "\r\n"; - } - else if($fieldType=="datetime") - { + } else if ($fieldType == "datetime") { $nowtime = GetDateTimeMk(time()); $innertext = ""; - } - else if($fieldType=='img'||$fieldType=='imgfile') - { - if($admintype=='diy') { + } else if ($fieldType == 'img' || $fieldType == 'imgfile') { + if ($admintype == 'diy') { $innertext = "\r\n"; + } else { + $innertext = " \r\n"; } - else { - $innertext = " \r\n"; - } - } - else if($fieldType=='media') - { - if($admintype=='diy') - { + } else if ($fieldType == 'media') { + if ($admintype == 'diy') { $innertext = "不支持的类型\r\n"; + } else { + $innertext = " \r\n"; } - else - { - $innertext = " \r\n"; - } - } - else if($fieldType=='addon') - { - if($admintype=='diy') - { + } else if ($fieldType == 'addon') { + if ($admintype == 'diy') { $innertext = "\r\n"; + } else { + $innertext = " \r\n"; } - else - { - $innertext = " \r\n"; - } - } - else if($fieldType=='int'||$fieldType=='float') - { - $dfvalue = ($ctag->GetAtt('default')!='' ? $ctag->GetAtt('default') : '0'); + } else if ($fieldType == 'int' || $fieldType == 'float') { + $dfvalue = ($ctag->GetAtt('default') != '' ? $ctag->GetAtt('default') : '0'); $innertext = " (填写数值)\r\n"; - } - else - { - $dfvalue = ($ctag->GetAtt('default')!='' ? $ctag->GetAtt('default') : ''); + } else { + $dfvalue = ($ctag->GetAtt('default') != '' ? $ctag->GetAtt('default') : ''); $innertext = "\r\n"; } - $formitem = str_replace("~name~",$ctag->GetAtt('itemname'),$formitem); - $formitem = str_replace("~form~",$innertext,$formitem); + $formitem = str_replace("~name~", $ctag->GetAtt('itemname'), $formitem); + $formitem = str_replace("~form~", $innertext, $formitem); return $formitem; } @@ -185,174 +142,127 @@ function GetFormItem($ctag, $admintype='admin') * @param string $fieldname 变量类型 * @return string */ -function GetFieldValue($dvalue, $dtype, $aid=0, $job='add', $addvar='', $admintype='admin', $fieldname='') +function GetFieldValue($dvalue, $dtype, $aid = 0, $job = 'add', $addvar = '', $admintype = 'admin', $fieldname = '') { global $cfg_basedir, $cfg_cmspath, $adminid, $cfg_ml, $cfg_cookie_encode; - if(!empty($adminid)) - { + if (!empty($adminid)) { $adminid = $adminid; - } - else - { + } else { $adminid = isset($cfg_ml) ? $cfg_ml->M_ID : 1; } - if($dtype=='int') - { - if($dvalue=='') - { + if ($dtype == 'int') { + if ($dvalue == '') { return 0; } return GetAlabNum($dvalue); - } - else if($dtype=='stepselect') - { + } else if ($dtype == 'stepselect') { $dvalue = trim(preg_replace("#[^0-9\.]#", "", $dvalue)); return $dvalue; - } - else if($dtype=='float') - { - if($dvalue=='') - { + } else if ($dtype == 'float') { + if ($dvalue == '') { return 0; } return GetAlabNum($dvalue); - } - else if($dtype=='datetime') - { - if($dvalue=='') - { + } else if ($dtype == 'datetime') { + if ($dvalue == '') { return 0; } return GetMkTime($dvalue); - } - else if($dtype=='checkbox') - { + } else if ($dtype == 'checkbox') { $okvalue = ''; - if(is_array($dvalue)) - { - $okvalue = join(',',$dvalue); + if (is_array($dvalue)) { + $okvalue = join(',', $dvalue); } return $okvalue; - } - else if($dtype=="htmltext") - { - if($admintype=='member' || $admintype=='diy') - { - $dvalue = HtmlReplace($dvalue,-1); + } else if ($dtype == "htmltext") { + if ($admintype == 'member' || $admintype == 'diy') { + $dvalue = HtmlReplace($dvalue, -1); } return $dvalue; - } - else if($dtype=="multitext") - { - if($admintype=='member' || $admintype=='diy') - { - $dvalue = HtmlReplace($dvalue,0); + } else if ($dtype == "multitext") { + if ($admintype == 'member' || $admintype == 'diy') { + $dvalue = HtmlReplace($dvalue, 0); } return $dvalue; - } - else if($dtype=="textdata") - { - $ipath = $cfg_cmspath."/data/textdata"; - $tpath = ceil($aid / 5000); - if(!is_dir($cfg_basedir.$ipath)) - { - MkdirAll($cfg_basedir.$ipath, $GLOBALS['cfg_dir_purview']); - } - if(!is_dir($cfg_basedir.$ipath.'/'.$tpath)) - { - MkdirAll($cfg_basedir.$ipath.'/'.$tpath,$GLOBALS['cfg_dir_purview']); - } - $ipath = $ipath.'/'.$tpath; - $filename = "{$ipath}/{$aid}-".cn_substr(md5($cfg_cookie_encode), 0, 16).".txt"; + } else if ($dtype == "textdata") { + $ipath = $cfg_cmspath . "/data/textdata"; + $tpath = ceil($aid / 5000); + if (!is_dir($cfg_basedir . $ipath)) { + MkdirAll($cfg_basedir . $ipath, $GLOBALS['cfg_dir_purview']); + } + if (!is_dir($cfg_basedir . $ipath . '/' . $tpath)) { + MkdirAll($cfg_basedir . $ipath . '/' . $tpath, $GLOBALS['cfg_dir_purview']); + } + $ipath = $ipath . '/' . $tpath; + $filename = "{$ipath}/{$aid}-" . cn_substr(md5($cfg_cookie_encode), 0, 16) . ".txt"; - //会员投稿内容安全处理 - if($admintype=='member' || $admintype=='diy') - { - $dvalue = HtmlReplace($dvalue, -1); - } - $fp = fopen($cfg_basedir.$filename,"w"); - fwrite($fp, stripslashes($dvalue)); - fclose($fp); - CloseFtp(); - return $filename; - } - else if($dtype=='img' || $dtype=='imgfile') - { - if(preg_match("#[\\|/]uploads[\\|/]userup#", $dvalue)) return $dvalue; - if($admintype=='diy') - { + //会员投稿内容安全处理 + if ($admintype == 'member' || $admintype == 'diy') { + $dvalue = HtmlReplace($dvalue, -1); + } + $fp = fopen($cfg_basedir . $filename, "w"); + fwrite($fp, stripslashes($dvalue)); + fclose($fp); + CloseFtp(); + return $filename; + } else if ($dtype == 'img' || $dtype == 'imgfile') { + if (preg_match("#[\\|/]uploads[\\|/]userup#", $dvalue)) { + return $dvalue; + } + + if ($admintype == 'diy') { $iurl = MemberUploads($fieldname, '', 0, 'image', '', -1, -1, false); return $iurl; } $iurl = stripslashes($dvalue); - if(trim($iurl)=='') - { + if (trim($iurl) == '') { return ''; } - $iurl = trim(str_replace($GLOBALS['cfg_basehost'],"",$iurl)); - $imgurl = "{dede:img text='' width='' height=''} ".$iurl." {/dede:img}"; - if(preg_match("/^http:\/\//i", $iurl) && $GLOBALS['cfg_isUrlOpen']) - { + $iurl = trim(str_replace($GLOBALS['cfg_basehost'], "", $iurl)); + $imgurl = "{dede:img text='' width='' height=''} " . $iurl . " {/dede:img}"; + if (preg_match("/^http:\/\//i", $iurl) && $GLOBALS['cfg_isUrlOpen']) { //远程图片 $reimgs = ''; - if($GLOBALS['cfg_isUrlOpen']) - { - $reimgs = GetRemoteImage($iurl,$adminid); - if(is_array($reimgs)) - { - if($dtype=='imgfile') - { + if ($GLOBALS['cfg_isUrlOpen']) { + $reimgs = GetRemoteImage($iurl, $adminid); + if (is_array($reimgs)) { + if ($dtype == 'imgfile') { $imgurl = $reimgs[1]; - } - else - { - $imgurl = "{dede:img text='' width='".$reimgs[1]."' height='".$reimgs[2]."'} ".$reimgs[0]." {/dede:img}"; + } else { + $imgurl = "{dede:img text='' width='" . $reimgs[1] . "' height='" . $reimgs[2] . "'} " . $reimgs[0] . " {/dede:img}"; } } - } - else - { - if($dtype=='imgfile') - { + } else { + if ($dtype == 'imgfile') { $imgurl = $iurl; - } - else - { - $imgurl = "{dede:img text='' width='' height=''} ".$iurl." {/dede:img}"; + } else { + $imgurl = "{dede:img text='' width='' height=''} " . $iurl . " {/dede:img}"; } } - } - else if($iurl != '') - { + } else if ($iurl != '') { //站内图片 - $imgfile = $cfg_basedir.$iurl; - if(is_file($imgfile)) - { + $imgfile = $cfg_basedir . $iurl; + if (is_file($imgfile)) { $info = ''; - $imginfos = GetImageSize($imgfile,$info); - if($dtype=="imgfile") - { + $imginfos = GetImageSize($imgfile, $info); + if ($dtype == "imgfile") { $imgurl = $iurl; - } - else - { - $imgurl = "{dede:img text='' width='".$imginfos[0]."' height='".$imginfos[1]."'} $iurl {/dede:img}"; + } else { + $imgurl = "{dede:img text='' width='" . $imginfos[0] . "' height='" . $imginfos[1] . "'} $iurl {/dede:img}"; } } } return addslashes($imgurl); - } - else if($dtype=='addon' && $admintype=='diy') - { - if(preg_match("#[\\|/]uploads[\\|/]userup#", $dvalue)) return $dvalue; - $dvalue = MemberUploads($fieldname,'', 0, 'addon', '', -1, -1, false); + } else if ($dtype == 'addon' && $admintype == 'diy') { + if (preg_match("#[\\|/]uploads[\\|/]userup#", $dvalue)) { + return $dvalue; + } + + $dvalue = MemberUploads($fieldname, '', 0, 'addon', '', -1, -1, false); return $dvalue; - } - else - { - if($admintype=='member' || $admintype=='diy') - { - $dvalue = HtmlReplace($dvalue,1); + } else { + if ($admintype == 'member' || $admintype == 'diy') { + $dvalue = HtmlReplace($dvalue, 1); } return $dvalue; } @@ -368,52 +278,43 @@ function GetFieldValue($dvalue, $dtype, $aid=0, $job='add', $addvar='', $adminty * @param string $fieldname 变量名称 * @return string */ -function GetFormItemValue($ctag, $fvalue, $admintype='admin', $fieldname='') +function GetFormItemValue($ctag, $fvalue, $admintype = 'admin', $fieldname = '') { - global $cfg_basedir,$dsql; + global $cfg_basedir, $dsql; $fieldname = $ctag->GetName(); $formitem = $formitem = GetSysTemplets("custom_fields_{$admintype}.htm"); $innertext = trim($ctag->GetInnerText()); - if($innertext!='') - { + if ($innertext != '') { $formitem = $innertext; } $ftype = $ctag->GetAtt('type'); $myformItem = ''; - if(preg_match("/select|radio|checkbox/i", $ftype)) - { - $items = explode(',',$ctag->GetAtt('default')); + if (preg_match("/select|radio|checkbox/i", $ftype)) { + $items = explode(',', $ctag->GetAtt('default')); } - if($ftype=='select') - { + if ($ftype == 'select') { $myformItem = "\r\n"; $innertext = $myformItem; - } - else if($ctag->GetAtt("type")=='stepselect') - { - global $hasSetEnumJs,$cfg_cmspath; - $cmspath = ( (empty($cfg_cmspath) || preg_match('/[/$]/', $cfg_cmspath)) ? $cfg_cmspath.'/' : $cfg_cmspath ); + } else if ($ctag->GetAtt("type") == 'stepselect') { + global $hasSetEnumJs, $cfg_cmspath; + $cmspath = ((empty($cfg_cmspath) || preg_match('/[/$]/', $cfg_cmspath)) ? $cfg_cmspath . '/' : $cfg_cmspath); $myformItem = ''; $myformItem .= "\r\n"; $myformItem .= "\r\n"; $myformItem .= "\r\n"; $myformItem .= "\r\n"; - if($hasSetEnumJs != 'hasset') - { - $myformItem .= ''."\r\n"; + if ($hasSetEnumJs != 'hasset') { + $myformItem .= '' . "\r\n"; $GLOBALS['hasSetEnumJs'] = 'hasset'; } $myformItem .= "\r\n"; @@ -421,41 +322,33 @@ function GetFormItemValue($ctag, $fvalue, $admintype='admin', $fieldname='') $formitem = str_replace('~name~', $ctag->GetAtt('itemname'), $formitem); $formitem = str_replace('~form~', $myformItem, $formitem); return $formitem; - } - else if($ftype=='radio') - { - if(is_array($items)) - { - foreach($items as $v) - { + } else if ($ftype == 'radio') { + if (is_array($items)) { + foreach ($items as $v) { $v = trim($v); - if($v=='') continue; - $myformItem.= ($fvalue==$v ? "$v\r\n" : "$v\r\n"); + if ($v == '') { + continue; + } + + $myformItem .= ($fvalue == $v ? "$v\r\n" : "$v\r\n"); } } $innertext = $myformItem; } //checkbox - else if($ftype=='checkbox') - { + else if ($ftype == 'checkbox') { $myformItem = ''; - $fvalues = explode(',',$fvalue); - if(is_array($items)) - { - foreach($items as $v) - { + $fvalues = explode(',', $fvalue); + if (is_array($items)) { + foreach ($items as $v) { $v = trim($v); - if($v=='') - { + if ($v == '') { continue; } - if(in_array($v,$fvalues)) - { + if (in_array($v, $fvalues)) { $myformItem .= "$v\r\n"; - } - else - { + } else { $myformItem .= "$v\r\n"; } } @@ -464,87 +357,56 @@ function GetFormItemValue($ctag, $fvalue, $admintype='admin', $fieldname='') } //文本数据的特殊处理 - else if($ftype=="textdata") - { - if(is_file($cfg_basedir.$fvalue)) - { - $fp = fopen($cfg_basedir.$fvalue,'r'); + else if ($ftype == "textdata") { + if (is_file($cfg_basedir . $fvalue)) { + $fp = fopen($cfg_basedir . $fvalue, 'r'); $okfvalue = ''; - while(!feof($fp)){ $okfvalue .= fgets($fp,1024); } + while (!feof($fp)) {$okfvalue .= fgets($fp, 1024);} fclose($fp); - } - else - { + } else { $okfvalue = ''; } - if($admintype=='admin') - { - $myformItem = GetEditor($fieldname,$okfvalue,350,'Basic','string')."\r\n \r\n "; - } - else - { - $myformItem = GetEditor($fieldname,$okfvalue,350,'Member','string')."\r\n \r\n "; + if ($admintype == 'admin') { + $myformItem = GetEditor($fieldname, $okfvalue, 350, 'Basic', 'string') . "\r\n \r\n "; + } else { + $myformItem = GetEditor($fieldname, $okfvalue, 350, 'Member', 'string') . "\r\n \r\n "; } $innertext = $myformItem; - } - else if($ftype=="htmltext") - { - if($admintype=='admin') - { - $myformItem = GetEditor($fieldname,$fvalue,350,'Basic','string')."\r\n "; - } - else - { - $myformItem = GetEditor($fieldname,$fvalue,350,'Member','string')."\r\n "; + } else if ($ftype == "htmltext") { + if ($admintype == 'admin') { + $myformItem = GetEditor($fieldname, $fvalue, 350, 'Basic', 'string') . "\r\n "; + } else { + $myformItem = GetEditor($fieldname, $fvalue, 350, 'Member', 'string') . "\r\n "; } $innertext = $myformItem; - } - else if($ftype=="multitext") - { + } else if ($ftype == "multitext") { $innertext = "\r\n"; - } - else if($ftype=="datetime") - { + } else if ($ftype == "datetime") { $nowtime = GetDateTimeMk($fvalue); $innertext = ""; - } - else if($ftype=="img") - { + } else if ($ftype == "img") { $ndtp = new DedeTagParse(); $ndtp->LoadSource($fvalue); - if(!is_array($ndtp->CTags)) - { + if (!is_array($ndtp->CTags)) { $ndtp->Clear(); - $fvalue = ""; - } - else - { + $fvalue = ""; + } else { $ntag = $ndtp->GetTag("img"); $fvalue = trim($ntag->GetInnerText()); } - $innertext = " \r\n"; - } - else if($ftype=="imgfile") - { - $innertext = " \r\n"; - } - else if($ftype=="media") - { - $innertext = " \r\n"; - } - else if($ftype=="addon") - { - $innertext = " \r\n"; - } - else if($ftype=="int"||$ftype=="float") - { + $innertext = " \r\n"; + } else if ($ftype == "imgfile") { + $innertext = " \r\n"; + } else if ($ftype == "media") { + $innertext = " \r\n"; + } else if ($ftype == "addon") { + $innertext = " \r\n"; + } else if ($ftype == "int" || $ftype == "float") { $innertext = " (填写数值)\r\n"; - } - else - { + } else { $innertext = "\r\n"; } - $formitem = str_replace('~name~',$ctag->GetAtt('itemname'),$formitem); - $formitem = str_replace('~form~',$innertext,$formitem); + $formitem = str_replace('~name~', $ctag->GetAtt('itemname'), $formitem); + $formitem = str_replace('~form~', $innertext, $formitem); return $formitem; -} \ No newline at end of file +} diff --git a/include/datalistcp.class.php b/include/datalistcp.class.php index e0a2709d..f99d7ee5 100755 --- a/include/datalistcp.class.php +++ b/include/datalistcp.class.php @@ -124,6 +124,10 @@ function SetTemplet($tplfile) { $this->tpl->LoadTemplate($tplfile); } + function SetString($src) + { + $this->tpl->LoadString($src); + } /** * 对config参数及get参数等进行预处理 diff --git a/include/dedecollection.class.php b/include/dedecollection.class.php index b7bdeea1..4fd810ec 100755 --- a/include/dedecollection.class.php +++ b/include/dedecollection.class.php @@ -1,4 +1,4 @@ -dsql = $GLOBALS['dsql']; $this->cHttpDown = new DedeHttpDown(); $this->cDedeHtml = new DedeHtml2(); } - function DedeCollection() + public function DedeCollection() { $this->__construct(); } //析放资源 - function Close() + public function Close() { } @@ -63,7 +63,7 @@ function Close() * @param int $nid 采集节点ID * @return void */ - function LoadNote($nid) + public function LoadNote($nid) { $this->noteId = $nid; $row = $this->dsql->GetOne("SELECT * FROM `#@__co_note` WHERE nid='$nid'"); @@ -78,19 +78,17 @@ function LoadNote($nid) * @param string $configString 配置字符串 * @return void */ - function LoadListConfig($configString) + public function LoadListConfig($configString) { $dtp = new DedeTagParse(); $dtp2 = new DedeTagParse(); $dtp->LoadString($configString); - for($i=0; $i<=$dtp->Count; $i++) - { + for ($i = 0; $i <= $dtp->Count; $i++) { $ctag = $dtp->CTags[$i]; //item 配置 //节点基本信息 - if($ctag->GetName()=="noteinfo") - { + if ($ctag->GetName() == "noteinfo") { $this->noteInfos['notename'] = $ctag->GetAtt('notename'); $this->noteInfos['matchtype'] = $ctag->GetAtt('matchtype'); $this->noteInfos['channelid'] = $ctag->GetAtt('channelid'); @@ -103,8 +101,7 @@ function LoadListConfig($configString) //list 配置 //要采集的列表页的信息 - else if($ctag->GetName()=="listrule") - { + else if ($ctag->GetName() == "listrule") { $this->lists['sourcetype'] = $ctag->GetAtt('sourcetype'); $this->lists['rssurl'] = $ctag->GetAtt('rssurl'); $this->lists['regxurl'] = $ctag->GetAtt('regxurl'); @@ -115,46 +112,33 @@ function LoadListConfig($configString) $this->lists['musthas'] = $ctag->GetAtt('musthas'); $this->lists['nothas'] = $ctag->GetAtt('nothas'); $this->lists['listpic'] = $ctag->GetAtt('listpic'); - $this->lists['usemore'] = $ctag->GetAtt('usemore'); + $this->lists['usemore'] = $ctag->GetAtt('usemore'); $dtp2->LoadString($ctag->GetInnerText()); - for($j=0; $j<=$dtp2->Count; $j++) - { + for ($j = 0; $j <= $dtp2->Count; $j++) { $ctag2 = $dtp2->CTags[$j]; $tname = $ctag2->GetName(); - if($tname=='addurls') - { + if ($tname == 'addurls') { $this->lists['addurls'] = trim($ctag2->GetInnerText()); - } - else if($tname=='regxrule') - { + } else if ($tname == 'regxrule') { $this->lists['regxrule'] = trim($ctag2->GetInnerText()); - } - else if($tname=='areastart') - { + } else if ($tname == 'areastart') { $this->lists['areastart'] = trim($ctag2->GetInnerText()); - } - else if($tname=='areaend') - { + } else if ($tname == 'areaend') { $this->lists['areaend'] = trim($ctag2->GetInnerText()); - } - else if($tname=='batchrule') - { + } else if ($tname == 'batchrule') { $this->lists['batchrule'] = trim($ctag2->GetInnerText()); } } //分析列表网址 - if($this->lists['sourcetype'] != 'rss') - { - $this->lists['url'] = GetUrlFromListRule($this->lists['regxurl'],$this->lists['addurls'], - $this->lists['startid'],$this->lists['endid'],$this->lists['addv'],$this->lists['usemore'],$this->lists['batchrule']); - } - else - { + if ($this->lists['sourcetype'] != 'rss') { + $this->lists['url'] = GetUrlFromListRule($this->lists['regxurl'], $this->lists['addurls'], + $this->lists['startid'], $this->lists['endid'], $this->lists['addv'], $this->lists['usemore'], $this->lists['batchrule']); + } else { $this->lists['url'] = $this->lists['rssurl']; } } - }//End Loop + } //End Loop $dtp->Clear(); $dtp2->Clear(); @@ -167,38 +151,27 @@ function LoadListConfig($configString) * @param string $configString 配置字符串 * @return void */ - function LoadItemConfig($configString) + public function LoadItemConfig($configString) { $dtp = new DedeTagParse(); $dtp2 = new DedeTagParse(); $dtp->LoadString($configString); - for($i=0; $i<=$dtp->Count; $i++) - { + for ($i = 0; $i <= $dtp->Count; $i++) { $ctag = $dtp->CTags[$i]; - if($ctag->GetName()=='sppage') - { + if ($ctag->GetName() == 'sppage') { $this->artNotes['sppage'] = $ctag->GetInnerText(); $this->artNotes['sptype'] = $ctag->GetAtt('sptype'); $this->spNotes['srul'] = $ctag->GetAtt('srul'); $this->spNotes['erul'] = $ctag->GetAtt('erul'); - } - else if($ctag->GetName()=='previewurl') - { + } else if ($ctag->GetName() == 'previewurl') { $this->artNotes['previewurl'] = $ctag->GetInnerText(); - } - else if($ctag->GetName()=='keywordtrim') - { + } else if ($ctag->GetName() == 'keywordtrim') { $this->artNotes['keywordtrim'] = $ctag->GetInnerText(); - } - else if($ctag->GetName()=='descriptiontrim') - { + } else if ($ctag->GetName() == 'descriptiontrim') { $this->artNotes['descriptiontrim'] = $ctag->GetInnerText(); - } - else if($ctag->GetName()=='item') - { + } else if ($ctag->GetName() == 'item') { $field = $ctag->GetAtt('field'); - if($field == '') - { + if ($field == '') { continue; } $this->artNotes[$field]['value'] = $ctag->GetAtt('value'); @@ -209,26 +182,20 @@ function LoadItemConfig($configString) $this->artNotes[$field]['function'] = ''; $t = 0; $dtp2->LoadString($ctag->GetInnerText()); - for($k=0; $k<=$dtp2->Count; $k++) - { + for ($k = 0; $k <= $dtp2->Count; $k++) { $ctag2 = $dtp2->CTags[$k]; - if($ctag2->GetName()=='trim') - { - $this->artNotes[$field]['trim'][$t][0] = str_replace('#n#',' ',$ctag2->GetInnerText()); + if ($ctag2->GetName() == 'trim') { + $this->artNotes[$field]['trim'][$t][0] = str_replace('#n#', ' ', $ctag2->GetInnerText()); $this->artNotes[$field]['trim'][$t][1] = $ctag2->GetAtt('replace'); $t++; - } - else if($ctag2->GetName()=='match') - { - $this->artNotes[$field]['match'] = str_replace('#n#',' ',$ctag2->GetInnerText()); - } - else if($ctag2->GetName()=='function') - { + } else if ($ctag2->GetName() == 'match') { + $this->artNotes[$field]['match'] = str_replace('#n#', ' ', $ctag2->GetInnerText()); + } else if ($ctag2->GetName() == 'function') { $this->artNotes[$field]['function'] = $ctag2->GetInnerText(); } } } - }//End Loop + } //End Loop $dtp->Clear(); $dtp2->Clear(); @@ -244,7 +211,7 @@ function LoadItemConfig($configString) * @param bool $issave 是否保存 * @return string */ - function DownUrl($aid, $dourl, $litpic='', $issave=TRUE) + public function DownUrl($aid, $dourl, $litpic = '', $issave = true) { $this->tmpLinks = array(); $this->tmpUnitValue = ''; @@ -252,25 +219,20 @@ function DownUrl($aid, $dourl, $litpic='', $issave=TRUE) $this->tmpHtml = $this->DownOnePage($dourl); //检测是否有分页字段,并预先处理 - if(!empty($this->artNotes['sppage'])) - { + if (!empty($this->artNotes['sppage'])) { $noteid = ''; - foreach($this->artNotes as $k=>$sarr) - { - if(isset($sarr['isunit']) && $sarr['isunit']==1) - { + foreach ($this->artNotes as $k => $sarr) { + if (isset($sarr['isunit']) && $sarr['isunit'] == 1) { $noteid = $k; break; } } - + $this->GetSpPage($dourl, $noteid, $this->tmpHtml); - if(preg_match("/#p#/i", $this->tmpUnitValue)) - { - if ($this->artNotes["sptype"] != 'diyrule') - { - $this->tmpUnitValue = '副标题#e#'.$this->tmpUnitValue; + if (preg_match("/#p#/i", $this->tmpUnitValue)) { + if ($this->artNotes["sptype"] != 'diyrule') { + $this->tmpUnitValue = '副标题#e#' . $this->tmpUnitValue; } } } @@ -279,46 +241,43 @@ function DownUrl($aid, $dourl, $litpic='', $issave=TRUE) $body = $this->GetPageFields($dourl, $issave, $litpic); //保存资料到数据库 - if($issave) - { - $query = " UPDATE `#@__co_htmls` SET dtime='".time()."',result='".addslashes($body)."',isdown='1' WHERE aid='$aid' "; - if(!$this->dsql->ExecuteNoneQuery($query)) - { + if ($issave) { + $query = " UPDATE `#@__co_htmls` SET dtime='" . time() . "',result='" . addslashes($body) . "',isdown='1' WHERE aid='$aid' "; + if (!$this->dsql->ExecuteNoneQuery($query)) { echo $this->dsql->GetError(); } return $body; } return $body; } - + // 解析地址 - function GetUrl($uri) + public function GetUrl($uri) { $arr = $tmp = array(); // query - $x = array_pad( explode( '?', $uri ), 2, false ); - $arr['query'] = ( $x[1] )? $x[1] : '' ; + $x = array_pad(explode('?', $uri), 2, false); + $arr['query'] = ($x[1]) ? $x[1] : ''; // resource - $x = array_pad( explode( '/', $x[0] ), 2, false ); - $x_last = array_pop( $x ); - if( strpos( $x_last, '.' ) === false ) - { + $x = array_pad(explode('/', $x[0]), 2, false); + $x_last = array_pop($x); + if (strpos($x_last, '.') === false) { $arr['resource'] = ''; $x[] = $x_last; - } - else - { + } else { $arr['resource'] = $x_last; $tmp = @explode('.', $arr['resource']); $arr['file'] = @$tmp[0]; - $arr['ext'] = '.'.@$tmp[1]; + $arr['ext'] = '.' . @$tmp[1]; } - // path - $arr['path'] = implode( '/', $x ); - if( substr( $arr['path'], -1 ) !== '/' ) $arr['path'] .= '/'; + // path + $arr['path'] = implode('/', $x); + if (substr($arr['path'], -1) !== '/') { + $arr['path'] .= '/'; + } // url $arr['url'] = $uri; @@ -336,118 +295,99 @@ function GetUrl($uri) * @param int $step 步骤 * @return string */ - function GetSpPage($dourl, $noteid, $html, $step=0) + public function GetSpPage($dourl, $noteid, $html, $step = 0) { $sarr = $this->artNotes[$noteid]; - + $linkareaHtml = $this->GetHtmlArea('[内容]', $this->artNotes['sppage'], $html); - if($linkareaHtml=='') - { - if($this->tmpUnitValue=='') - { + if ($linkareaHtml == '') { + if ($this->tmpUnitValue == '') { $this->tmpUnitValue .= $this->GetHtmlArea('[内容]', $sarr['match'], $html); + } else { + $this->tmpUnitValue .= "#p#副标题#e#" . $this->GetHtmlArea('[内容]', $sarr['match'], $html); } - else - { - $this->tmpUnitValue .= "#p#副标题#e#".$this->GetHtmlArea('[内容]', $sarr['match'], $html); + if ($this->artNotes["sptype"] != 'diyrule') { + return; } - if ($this->artNotes["sptype"] != 'diyrule') return; - + } - //完整的分页列表 - if($this->artNotes["sptype"]=='full' || $this->artNotes["sptype"]=='') - { + if ($this->artNotes["sptype"] == 'full' || $this->artNotes["sptype"] == '') { $this->tmpUnitValue .= $this->GetHtmlArea('[内容]', $sarr['match'], $html); $this->cDedeHtml->GetLinkType = "link"; $this->cDedeHtml->SetSource($linkareaHtml, $dourl, 'link'); - foreach($this->cDedeHtml->Links as $k=>$t) - { + foreach ($this->cDedeHtml->Links as $k => $t) { $k = $this->cDedeHtml->FillUrl($k); - if($k==$dourl) - { + if ($k == $dourl) { continue; } $nhtml = $this->DownOnePage($k); - if($nhtml!='') - { + if ($nhtml != '') { $ct = trim($this->GetHtmlArea('[内容]', $sarr['match'], $nhtml)); - if($ct!='') - { - $this->tmpUnitValue .= "#p#副标题#e#".$ct; + if ($ct != '') { + $this->tmpUnitValue .= "#p#副标题#e#" . $ct; } } } - } - else if ($this->artNotes["sptype"] == 'diyrule') - { + } else if ($this->artNotes["sptype"] == 'diyrule') { $maxpage = 10; $urlinfo = $this->GetUrl($dourl); $testurl = str_replace(array_keys($urlinfo), array_values($urlinfo), $this->artNotes['sppage']); $testurl = str_ireplace('{p}', '~p~', $testurl); $testurl = str_replace(array('{', '}'), '', $testurl); $lastchash = md5($html); - for($i=$this->spNotes['srul']; $i <= $this->spNotes['erul']; $i++) - { + for ($i = $this->spNotes['srul']; $i <= $this->spNotes['erul']; $i++) { $tempurl = str_replace('~p~', $i, $testurl); $tempurl = $this->cDedeHtml->FillUrl($tempurl); $nhtml = $this->DownOnePage($tempurl); $newchash = md5($nhtml); - if ($newchash == $lastchash) continue; + if ($newchash == $lastchash) { + continue; + } + $lastchash = $newchash; - - if($nhtml!='') - { + + if ($nhtml != '') { $ct = trim($this->GetHtmlArea('[内容]', $sarr['match'], $nhtml)); - if($ct!='') - { - $this->tmpUnitValue .= "#p#副标题#e#".$ct; + if ($ct != '') { + $this->tmpUnitValue .= "#p#副标题#e#" . $ct; // echo $this->tmpUnitValue;exit; } } } } //上下页形式或不完整的分页列表 - else - { - if($step>50) - { + else { + if ($step > 50) { return; } - if($step==0) - { + if ($step == 0) { $this->tmpUnitValue .= $this->GetHtmlArea('[内容]', $sarr['match'], $html); } $this->cDedeHtml->GetLinkType = "link"; $this->cDedeHtml->SetSource($linkareaHtml, $dourl, 'link'); - $hasLink = FALSE; - foreach($this->cDedeHtml->Links as $k=>$t) - { + $hasLink = false; + foreach ($this->cDedeHtml->Links as $k => $t) { $k = $this->cDedeHtml->FillUrl($k); - if(in_array($k, $this->tmpLinks)) - { - CONTINUE; - } - else{ + if (in_array($k, $this->tmpLinks)) { + continue; + } else { $nhtml = $this->DownOnePage($k); - if($nhtml!='') - { - $ct = trim($this->GetHtmlArea('[内容]',$sarr['match'],$nhtml)); - if($ct!='') - { - $this->tmpUnitValue .= "#p#副标题#e#".$ct; + if ($nhtml != '') { + $ct = trim($this->GetHtmlArea('[内容]', $sarr['match'], $nhtml)); + if ($ct != '') { + $this->tmpUnitValue .= "#p#副标题#e#" . $ct; } } - $hasLink = TRUE; + $hasLink = true; $this->tmpLinks[] = $k; $dourl = $k; $step++; } } - if($hasLink) - { + if ($hasLink) { $this->GetSpPage($dourl, $noteid, $nhtml, $step); } } @@ -462,44 +402,36 @@ function GetSpPage($dourl, $noteid, $html, $step=0) * @param string $html html代码 * @return string */ - function GetHtmlArea($sptag, &$areaRule, &$html) + public function GetHtmlArea($sptag, &$areaRule, &$html) { //用正则表达式的模式匹配 - if($this->noteInfos['matchtype']=='regex') - { + if ($this->noteInfos['matchtype'] == 'regex') { $areaRule = str_replace("/", "\\/", $areaRule); $areaRules = explode($sptag, $areaRule); $arr = array(); - if($html==''||$areaRules[0]=='') - { + if ($html == '' || $areaRules[0] == '') { return ''; } - preg_match('#'.$areaRules[0]."(.*)".$areaRules[1]."#isU", $html, $arr); + preg_match('#' . $areaRules[0] . "(.*)" . $areaRules[1] . "#isU", $html, $arr); return empty($arr[1]) ? '' : trim($arr[1]); } //用字符串模式匹配 - else - { - $areaRules = explode($sptag,$areaRule); - if($html=='' || $areaRules[0]=='') - { + else { + $areaRules = explode($sptag, $areaRule); + if ($html == '' || $areaRules[0] == '') { return ''; } - $posstart = @strpos($html,$areaRules[0]); - if($posstart===FALSE) - { + $posstart = @strpos($html, $areaRules[0]); + if ($posstart === false) { return ''; } $posstart = $posstart + strlen($areaRules[0]); - $posend = @strpos($html,$areaRules[1],$posstart); - if($posend > $posstart && $posend!==FALSE) - { + $posend = @strpos($html, $areaRules[1], $posstart); + if ($posend > $posstart && $posend !== false) { //return substr($html,$posstart+strlen($areaRules[0]),$posend-$posstart-strlen($areaRules[0])); - return substr($html,$posstart,$posend-$posstart); - } - else - { + return substr($html, $posstart, $posend - $posstart); + } else { return ''; } } @@ -511,7 +443,7 @@ function GetHtmlArea($sptag, &$areaRule, &$html) * @access public * @param string $dourl 下载地址 */ - function DownOnePage($dourl) + public function DownOnePage($dourl) { $this->cHttpDown->OpenUrl($dourl); $html = $this->cHttpDown->GetHtml(); @@ -529,94 +461,77 @@ function DownOnePage($dourl) * @param string $islitpic 是否缩略图 * @return string */ - function DownMedia($dourl, $mtype='img', $islitpic=FALSE) + public function DownMedia($dourl, $mtype = 'img', $islitpic = false) { global $notckpic; - if(empty($notckpic)) - { + if (empty($notckpic)) { $notckpic = 0; } //检测是否已经下载此文件 - $wi = FALSE; + $wi = false; $tofile = $filename = ''; - if($notckpic==0) - { - $row = $this->dsql->GetOne("SELECT hash,tofile FROM `#@__co_mediaurls` WHERE nid='{$this->noteId}' AND hash='".md5($dourl)."' "); - if(isset($row['tofile'])) - { + if ($notckpic == 0) { + $row = $this->dsql->GetOne("SELECT hash,tofile FROM `#@__co_mediaurls` WHERE nid='{$this->noteId}' AND hash='" . md5($dourl) . "' "); + if (isset($row['tofile'])) { $tofile = $filename = $row['tofile']; } } //如果不存在,下载文件 - if($tofile=='' || !file_exists($GLOBALS['cfg_basedir'].$filename)) - { - $filename = $this->GetRndName($dourl,$mtype); - if(!preg_match("#^\/#", $filename)) - { - $filename = "/".$filename; + if ($tofile == '' || !file_exists($GLOBALS['cfg_basedir'] . $filename)) { + $filename = $this->GetRndName($dourl, $mtype); + if (!preg_match("#^\/#", $filename)) { + $filename = "/" . $filename; } //防盗链模式 - if($this->noteInfos['isref']=='yes' && $this->noteInfos['refurl']!='') - { - if($this->noteInfos['exptime']=='') - { + if ($this->noteInfos['isref'] == 'yes' && $this->noteInfos['refurl'] != '') { + if ($this->noteInfos['exptime'] == '') { $this->noteInfos['exptime'] = 10; } - DownImageKeep($dourl,$this->noteInfos['refurl'],$GLOBALS['cfg_basedir'].$filename,'',0,$this->Item['exptime']); + DownImageKeep($dourl, $this->noteInfos['refurl'], $GLOBALS['cfg_basedir'] . $filename, '', 0, $this->Item['exptime']); } //普通模式 - else - { + else { $this->cHttpDown->OpenUrl($dourl); - $this->cHttpDown->SaveToBin($GLOBALS['cfg_basedir'].$filename); + $this->cHttpDown->SaveToBin($GLOBALS['cfg_basedir'] . $filename); $this->cHttpDown->Close(); } //下载文件成功,保存记录 - if(file_exists($GLOBALS['cfg_basedir'].$filename)) - { - if($tofile=='') - { - $query = "INSERT INTO `#@__co_mediaurls`(nid,hash,tofile) VALUES ('".$this->noteId."', '".md5($dourl)."', '".addslashes($filename)."');"; - } - else - { - $query = "UPDATE `#@__co_mediaurls` SET tofile='".addslashes($filename)."' WHERE hash='".md5($dourl)."' "; + if (file_exists($GLOBALS['cfg_basedir'] . $filename)) { + if ($tofile == '') { + $query = "INSERT INTO `#@__co_mediaurls`(nid,hash,tofile) VALUES ('" . $this->noteId . "', '" . md5($dourl) . "', '" . addslashes($filename) . "');"; + } else { + $query = "UPDATE `#@__co_mediaurls` SET tofile='" . addslashes($filename) . "' WHERE hash='" . md5($dourl) . "' "; } $this->dsql->ExecuteNoneQuery($query); } } //如果下载图片失败或图片不存在,返回网址 - if(!file_exists($GLOBALS['cfg_basedir'].$filename)) - { + if (!file_exists($GLOBALS['cfg_basedir'] . $filename)) { return $dourl; } //生成缩略图 - if($mtype=='img' && !$islitpic && $this->breImage=='') - { + if ($mtype == 'img' && !$islitpic && $this->breImage == '') { $this->breImage = $filename; - if(!preg_match("#^http:\/\/#", $this->breImage) && file_exists($GLOBALS['cfg_basedir'].$filename)) - { - $filenames = explode('/',$filename); - $filenamed = $filenames[count($filenames)-1]; - $nfilename = str_replace('.','_lit.',$filenamed); - $nfilename = str_replace($filenamed,$nfilename,$filename); - if(@copy($GLOBALS['cfg_basedir'].$filename, $GLOBALS['cfg_basedir'].$nfilename)) - { - ImageResize($GLOBALS['cfg_basedir'].$nfilename,$GLOBALS['cfg_ddimg_width'],$GLOBALS['cfg_ddimg_height']); + if (!preg_match("#^http:\/\/#", $this->breImage) && file_exists($GLOBALS['cfg_basedir'] . $filename)) { + $filenames = explode('/', $filename); + $filenamed = $filenames[count($filenames) - 1]; + $nfilename = str_replace('.', '_lit.', $filenamed); + $nfilename = str_replace($filenamed, $nfilename, $filename); + if (@copy($GLOBALS['cfg_basedir'] . $filename, $GLOBALS['cfg_basedir'] . $nfilename)) { + ImageResize($GLOBALS['cfg_basedir'] . $nfilename, $GLOBALS['cfg_ddimg_width'], $GLOBALS['cfg_ddimg_height']); $this->breImage = $nfilename; } } } - if($mtype=='img' && !$islitpic) - { - @WaterImg($GLOBALS['cfg_basedir'].$filename,'collect'); + if ($mtype == 'img' && !$islitpic) { + @WaterImg($GLOBALS['cfg_basedir'] . $filename, 'collect'); } return $filename; } @@ -629,57 +544,46 @@ function DownMedia($dourl, $mtype='img', $islitpic=FALSE) * @param string $v 值 * @return string */ - function GetRndName($url, $v) + public function GetRndName($url, $v) { - global $cfg_image_dir,$cfg_dir_purview; + global $cfg_image_dir, $cfg_dir_purview; $this->mediaCount++; $mnum = $this->mediaCount; - $timedir = "c".MyDate("ymd",time()); + $timedir = "c" . MyDate("ymd", time()); //存放路径 - $fullurl = preg_replace("#\/{1,}#", "/", $cfg_image_dir."/"); - if(!is_dir($GLOBALS['cfg_basedir']."/$fullurl")) - { - MkdirAll($GLOBALS['cfg_basedir']."/$fullurl", $cfg_dir_purview); + $fullurl = preg_replace("#\/{1,}#", "/", $cfg_image_dir . "/"); + if (!is_dir($GLOBALS['cfg_basedir'] . "/$fullurl")) { + MkdirAll($GLOBALS['cfg_basedir'] . "/$fullurl", $cfg_dir_purview); } - $fullurl = $fullurl.$timedir."/"; - if(!is_dir($GLOBALS['cfg_basedir']."/$fullurl")) - { - MkdirAll($GLOBALS['cfg_basedir']."/$fullurl", $cfg_dir_purview); + $fullurl = $fullurl . $timedir . "/"; + if (!is_dir($GLOBALS['cfg_basedir'] . "/$fullurl")) { + MkdirAll($GLOBALS['cfg_basedir'] . "/$fullurl", $cfg_dir_purview); } //文件名称 - $timename = str_replace('.','', ExecTime()); + $timename = str_replace('.', '', ExecTime()); $threadnum = 0; - if(isset($_GET['threadnum'])) - { + if (isset($_GET['threadnum'])) { $threadnum = intval($_GET['threadnum']); } - $filename = dd2char($timename.$threadnum.'-'.$mnum.mt_rand(1000,9999)); + $filename = dd2char($timename . $threadnum . '-' . $mnum . mt_rand(1000, 9999)); //分配扩展名 - $urls = explode('.',$url); - if($v=='img') - { + $urls = explode('.', $url); + if ($v == 'img') { $shortname = '.jpg'; - if(preg_match("#\.gif$#i", $url)) - { + if (preg_match("#\.gif$#i", $url)) { $shortname = '.gif'; - } - else if(preg_match("#\.png$#i", $url)) - { + } else if (preg_match("#\.png$#i", $url)) { $shortname = '.png'; } - } - else if($v=='embed') - { + } else if ($v == 'embed') { $shortname = '.swf'; - } - else - { + } else { $shortname = ''; } - $fullname = $fullurl.$filename.$shortname; + $fullname = $fullurl . $filename . $shortname; return preg_replace("#\/{1,}#", "/", $fullname); } @@ -692,121 +596,91 @@ function GetRndName($url, $v) * @param string $litpic 缩略图 * @return string */ - function GetPageFields($dourl, $needDown, $litpic='') + public function GetPageFields($dourl, $needDown, $litpic = '') { global $cfg_auot_description; - if($this->tmpHtml == '') - { + if ($this->tmpHtml == '') { return ''; } $artitem = ''; - $isPutUnit = FALSE; + $isPutUnit = false; $tmpLtKeys = array(); $inarr = array(); //自动分析关键字和摘要 preg_match("#tmpHtml, $inarr); preg_match("#tmpHtml, $inarr2); - if(!isset($inarr[1]) && isset($inarr2[1])) - { + if (!isset($inarr[1]) && isset($inarr2[1])) { $inarr[1] = $inarr2[1]; } - if(isset($inarr[1])) - { - $keywords = trim(cn_substr(html2text($inarr[1]),30)); - $keywords = preg_replace("#".$this->artNotes['keywordtrim']."#isU",'',$keywords); - if(!preg_match("#,#", $keywords)) - { + if (isset($inarr[1])) { + $keywords = trim(cn_substr(html2text($inarr[1]), 30)); + $keywords = preg_replace("#" . $this->artNotes['keywordtrim'] . "#isU", '', $keywords); + if (!preg_match("#,#", $keywords)) { $keywords = str_replace(' ', ',', $keywords); } - $artitem .= "{dede:field name='keywords'}".$keywords."{/dede:field}\r\n"; - } - else - { + $artitem .= "{dede:field name='keywords'}" . $keywords . "{/dede:field}\r\n"; + } else { $artitem .= "{dede:field name='keywords'}{/dede:field}\r\n"; } // preg_match("#tmpHtml, $inarr); // preg_match("#tmpHtml, $inarr2); preg_match("#]*?)['\"]#iU", $this->tmpHtml, $inarr); preg_match("#]*?)['\"][\s]+name=['\"]description['\"]#iU", $this->tmpHtml, $inarr2); - if(!isset($inarr[1]) && isset($inarr2[1])) - { + if (!isset($inarr[1]) && isset($inarr2[1])) { $inarr[1] = $inarr2[1]; } - if(isset($inarr[1])) - { - $description = trim(cn_substr(html2text($inarr[1]),$cfg_auot_description)); - $description = preg_replace("/".$this->artNotes['descriptiontrim']."/isU",'',$description); - $artitem .= "{dede:field name='description'}".$description."{/dede:field}\r\n"; - } - else - { + if (isset($inarr[1])) { + $description = trim(cn_substr(html2text($inarr[1]), $cfg_auot_description)); + $description = preg_replace("/" . $this->artNotes['descriptiontrim'] . "/isU", '', $description); + $artitem .= "{dede:field name='description'}" . $description . "{/dede:field}\r\n"; + } else { $artitem .= "{dede:field name='description'}{/dede:field}\r\n"; } - foreach($this->artNotes as $k=>$sarr) - { + foreach ($this->artNotes as $k => $sarr) { //可能出现意外的情况 - if($k=='sppage' || $k=='sptype') - { + if ($k == 'sppage' || $k == 'sptype') { continue; } - if(!is_array($sarr)) - { + if (!is_array($sarr)) { continue; } //特殊的规则或没匹配选项 - if($sarr['match']=='' || trim($sarr['match'])=='[内容]') - { - if($sarr['value']!='[内容]') - { + if ($sarr['match'] == '' || trim($sarr['match']) == '[内容]') { + if ($sarr['value'] != '[内容]') { $v = trim($sarr['value']); - } - else - { + } else { $v = ''; } - } - else - { + } else { //分多页的内容 - if($this->tmpUnitValue!='' && !$isPutUnit && $sarr['isunit']==1) - { + if ($this->tmpUnitValue != '' && !$isPutUnit && $sarr['isunit'] == 1) { $v = $this->tmpUnitValue; - $isPutUnit = TRUE; - } - else - { - $v = $this->GetHtmlArea('[内容]',$sarr['match'],$this->tmpHtml); + $isPutUnit = true; + } else { + $v = $this->GetHtmlArea('[内容]', $sarr['match'], $this->tmpHtml); } //过滤内容规则 - if(isset($sarr['trim']) && $v!='') - { - foreach($sarr['trim'] as $nv) - { - if($nv[0]=='') - { + if (isset($sarr['trim']) && $v != '') { + foreach ($sarr['trim'] as $nv) { + if ($nv[0] == '') { continue; } $nvs = str_replace("/", "\\/", $nv[0]); - $v = preg_replace("#".$nvs."#isU", $nv[1], $v); + $v = preg_replace("#" . $nvs . "#isU", $nv[1], $v); } } //是否下载远程资源 - if($needDown) - { - if($sarr['isdown'] == '1') - { + if ($needDown) { + if ($sarr['isdown'] == '1') { $v = $this->DownMedias($v, $dourl); } - } - else - { - if($sarr['isdown'] == '1') - { + } else { + if ($sarr['isdown'] == '1') { $v = $this->MediasReplace($v, $dourl); } } @@ -814,34 +688,27 @@ function GetPageFields($dourl, $needDown, $litpic='') $v = trim($v); //用户自行对内容进行处理的接口 - if($sarr['function'] != '') - { + if ($sarr['function'] != '') { $tmpLtKeys[$k]['v'] = $v; $tmpLtKeys[$k]['f'] = $sarr['function']; - } - else - { + } else { $v = preg_replace("#( )$#", '', $v); $v = preg_replace("#[\r\n\t ]{1,}$#", '', $v); $artitem .= "{dede:field name='$k'}$v{/dede:field}\r\n"; } - }//End Foreach + } //End Foreach //处理带函数的项目 - foreach($tmpLtKeys as $k=>$sarr) - { - $v = $this->RunPHP($sarr['v'],$sarr['f']); + foreach ($tmpLtKeys as $k => $sarr) { + $v = $this->RunPHP($sarr['v'], $sarr['f']); $v = preg_replace("#( )$#", '', $v); $v = preg_replace("#[\r\n\t ]{1,}$#", '', $v); $artitem .= "{dede:field name='$k'}$v{/dede:field}\r\n"; } - if($litpic!='' && $this->lists['listpic']==1) - { - $artitem .= "{dede:field name='litpic'}".$this->DownMedia($litpic,'img',TRUE)."{/dede:field}\r\n"; - } - else - { - $artitem .= "{dede:field name='litpic'}".$this->breImage."{/dede:field}\r\n"; + if ($litpic != '' && $this->lists['listpic'] == 1) { + $artitem .= "{dede:field name='litpic'}" . $this->DownMedia($litpic, 'img', true) . "{/dede:field}\r\n"; + } else { + $artitem .= "{dede:field name='litpic'}" . $this->breImage . "{/dede:field}\r\n"; } return $artitem; } @@ -854,16 +721,14 @@ function GetPageFields($dourl, $needDown, $litpic='') * @param string $url 地址 * @return string */ - function DownMedias(&$html, $url) + public function DownMedias(&$html, $url) { - $this->cDedeHtml->SetSource($html,$url,'media'); + $this->cDedeHtml->SetSource($html, $url, 'media'); //下载标记里的图片和flash - foreach($this->cDedeHtml->Medias as $k=>$v) - { + foreach ($this->cDedeHtml->Medias as $k => $v) { $furl = $this->cDedeHtml->FillUrl($k); - if($v=='embed' && !preg_match("#\.(swf)\?(.*)$#i", $k)&& !preg_match("#\.(swf)$#i", $k)) - { + if ($v == 'embed' && !preg_match("#\.(swf)\?(.*)$#i", $k) && !preg_match("#\.(swf)$#i", $k)) { continue; } $okurl = $this->DownMedia($furl, $v); @@ -871,18 +736,12 @@ function DownMedias(&$html, $url) } //下载超链接里的图片 - foreach($this->cDedeHtml->Links as $v=>$k) - { - if(preg_match("#\.(jpg|gif|png)\?(.*)$#i",$v) || preg_match("#\.(jpg|gif|png)$#i", $v)) - { + foreach ($this->cDedeHtml->Links as $v => $k) { + if (preg_match("#\.(jpg|gif|png)\?(.*)$#i", $v) || preg_match("#\.(jpg|gif|png)$#i", $v)) { $m = "img"; - } - else if(preg_match("#\.(swf)\?(.*)$#i", $v) || preg_match("#\.(swf)$#i", $v)) - { + } else if (preg_match("#\.(swf)\?(.*)$#i", $v) || preg_match("#\.(swf)$#i", $v)) { $m = "embed"; - } - else - { + } else { continue; } $furl = $this->cDedeHtml->FillUrl($v); @@ -900,11 +759,10 @@ function DownMedias(&$html, $url) * @param string $dourl 操作地址 * @return string */ - function MediasReplace(&$html, $dourl) + public function MediasReplace(&$html, $dourl) { $this->cDedeHtml->SetSource($html, $dourl, 'media'); - foreach($this->cDedeHtml->Medias as $k=>$v) - { + foreach ($this->cDedeHtml->Medias as $k => $v) { $k = trim($k); $okurl = $this->cDedeHtml->FillUrl($k); $html = str_replace($k, $okurl, $html); @@ -913,57 +771,46 @@ function MediasReplace(&$html, $dourl) } //测试列表 - function Testlists(&$dourl) + public function Testlists(&$dourl) { $links = array(); //从RSS中获取网址 - if($this->lists['sourcetype']=='rss') - { + if ($this->lists['sourcetype'] == 'rss') { $dourl = $this->lists['rssurl']; $links = GetRssLinks($dourl); return $links; } //正常情况 - if(isset($this->lists['url'][0][0])) - { + if (isset($this->lists['url'][0][0])) { $dourl = $this->lists['url'][0][0]; - } - else - { + } else { $dourl = ''; $this->errString = "配置中指定列表的网址错误!\r\n"; return $links; } $dhtml = new DedeHtml2(); $html = $this->DownOnePage($dourl); - if($html=='') - { + if ($html == '') { $this->errString = "读取网址: $dourl 时失败!\r\n"; return $links; } - if( trim($this->lists['areastart']) !='' && trim($this->lists['areaend']) != '' ) - { - $areabody = $this->lists['areastart'].'[var:区域]'.$this->lists['areaend']; - $html = $this->GetHtmlArea('[var:区域]',$areabody,$html); + if (trim($this->lists['areastart']) != '' && trim($this->lists['areaend']) != '') { + $areabody = $this->lists['areastart'] . '[var:区域]' . $this->lists['areaend']; + $html = $this->GetHtmlArea('[var:区域]', $areabody, $html); } $t1 = ExecTime(); - $dhtml->SetSource($html,$dourl,'link'); - $this->lists['musthas'] = str_replace('/', '\/', $this->lists['musthas']); - foreach($dhtml->Links as $s) - { - if($this->lists['nothas']!='') - { - if( preg_match("#".$this->lists['nothas']."#i", $s['link']) ) - { + $dhtml->SetSource($html, $dourl, 'link'); + $this->lists['musthas'] = str_replace('/', '\/', $this->lists['musthas']); + foreach ($dhtml->Links as $s) { + if ($this->lists['nothas'] != '') { + if (preg_match("#" . $this->lists['nothas'] . "#i", $s['link'])) { continue; } } - if($this->lists['musthas']!='') - { - if( !preg_match("#".$this->lists['musthas']."#i", $s['link']) ) - { + if ($this->lists['musthas'] != '') { + if (!preg_match("#" . $this->lists['musthas'] . "#i", $s['link'])) { continue; } } @@ -979,9 +826,9 @@ function Testlists(&$dourl) * @param $dourl 操作地址 * @return string */ - function TestArt($dourl) + public function TestArt($dourl) { - return $this->DownUrl(0, $dourl, '', FALSE); + return $this->DownUrl(0, $dourl, '', false); } /** @@ -993,96 +840,81 @@ function TestArt($dourl) * @param int $pagesize 分页尺寸 * @return string */ - function GetSourceUrl($islisten=0, $glstart=0, $pagesize=10) + public function GetSourceUrl($islisten = 0, $glstart = 0, $pagesize = 10) { //在第一页中进行预处理 //“下载种子网址的未下载内容”的模式不需要经过采集种子网址的步骤 - if($glstart==0) - { + if ($glstart == 0) { //重新采集所有内容模式 - if($islisten == -1) - { - $this->dsql->ExecuteNoneQuery("DELETE FROM `#@__co_urls` WHERE nid='".$this->noteId."'"); - $this->dsql->ExecuteNoneQuery("DELETE FROM `#@__co_htmls` WHERE nid='".$this->noteId."' "); + if ($islisten == -1) { + $this->dsql->ExecuteNoneQuery("DELETE FROM `#@__co_urls` WHERE nid='" . $this->noteId . "'"); + $this->dsql->ExecuteNoneQuery("DELETE FROM `#@__co_htmls` WHERE nid='" . $this->noteId . "' "); } //监听模式(保留未导出的内容、保留节点的历史网址记录) - else - { - $this->dsql->ExecuteNoneQuery("DELETE FROM `#@__co_htmls` WHERE nid='".$this->noteId."' AND isexport=1 "); + else { + $this->dsql->ExecuteNoneQuery("DELETE FROM `#@__co_htmls` WHERE nid='" . $this->noteId . "' AND isexport=1 "); } } //从RSS中获取种子 - if($this->lists['sourcetype']=='rss') - { + if ($this->lists['sourcetype'] == 'rss') { $links = GetRssLinks($this->lists['rssurl']); //if($this->noteInfos['cosort']!='asc') $tmplink = krsort($links); $lk = 0; - foreach($links as $v) - { - if($islisten==1) - { - $lrow = $this->dsql->GetOne("SELECT * FROM `#@__co_urls` WHERE nid='{$this->noteId}' AND hash='".md5($v['link'])."' "); - if(is_array($lrow)) - { + foreach ($links as $v) { + if ($islisten == 1) { + $lrow = $this->dsql->GetOne("SELECT * FROM `#@__co_urls` WHERE nid='{$this->noteId}' AND hash='" . md5($v['link']) . "' "); + if (is_array($lrow)) { continue; } } $lk++; - if($mytotal > 0 && $lk >= $mytotal) break; + if ($mytotal > 0 && $lk >= $mytotal) { + break; + } + $inquery = "INSERT INTO `#@__co_htmls` (`nid` ,`typeid`, `title` , `litpic` , `url` , `dtime` , `isdown` , `isexport` , `result`) - VALUES ('{$this->noteId}' , '0', '".addslashes($v['title'])."' , '".addslashes($v['image'])."' , '".addslashes($v['link'])."' , 'dtime' , '0' , '0' , ''); "; + VALUES ('{$this->noteId}' , '0', '" . addslashes($v['title']) . "' , '" . addslashes($v['image']) . "' , '" . addslashes($v['link']) . "' , 'dtime' , '0' , '0' , ''); "; $this->dsql->ExecuteNoneQuery($inquery); - $inquery = "INSERT INTO `#@__co_urls`(hash,nid) VALUES ('".md5($v['link'])."','{$this->noteId}');"; + $inquery = "INSERT INTO `#@__co_urls`(hash,nid) VALUES ('" . md5($v['link']) . "','{$this->noteId}');"; $this->dsql->ExecuteNoneQuery($inquery); } return 0; - } - else - { + } else { $tmplink = array(); $arrStart = 0; $moviePostion = 0; $endpos = $glstart + $pagesize; $totallen = count($this->lists['url']); - //dump($this->lists['url']);exit; - foreach($this->lists['url'] as $k=>$cururls) - { + //dump($this->lists['url']);exit; + foreach ($this->lists['url'] as $k => $cururls) { //$status = FALSE; $urlnum = 0; $cururl = $cururls[0]; $typeid = (empty($cururls[1]) ? 0 : $cururls[1]); $moviePostion++; - - if($moviePostion > $endpos) - { + + if ($moviePostion > $endpos) { break; } - if($moviePostion > $glstart) - { + if ($moviePostion > $glstart) { $html = $this->DownOnePage($cururl); - if( trim($this->lists['areastart']) !='' && trim($this->lists['areaend']) != '' ) - { - $areabody = $this->lists['areastart'].'[var:区域]'.$this->lists['areaend']; - $html = $this->GetHtmlArea('[var:区域]',$areabody,$html); + if (trim($this->lists['areastart']) != '' && trim($this->lists['areaend']) != '') { + $areabody = $this->lists['areastart'] . '[var:区域]' . $this->lists['areaend']; + $html = $this->GetHtmlArea('[var:区域]', $areabody, $html); } $this->cDedeHtml->SetSource($html, $cururl, 'link'); $lk = 0; - foreach($this->cDedeHtml->Links as $k=>$v) - { - if($this->lists['nothas']!='') - { - if( preg_match("#".$this->lists['nothas']."#", $v['link']) ) - { + foreach ($this->cDedeHtml->Links as $k => $v) { + if ($this->lists['nothas'] != '') { + if (preg_match("#" . $this->lists['nothas'] . "#", $v['link'])) { continue; } } - if($this->lists['musthas']!='') - { - if( !preg_match("#".$this->lists['musthas']."#i", $v['link']) ) - { + if ($this->lists['musthas'] != '') { + if (!preg_match("#" . $this->lists['musthas'] . "#i", $v['link'])) { continue; } } @@ -1093,58 +925,45 @@ function GetSourceUrl($islisten=0, $glstart=0, $pagesize=10) } $this->cDedeHtml->Clear(); } - }//foreach + } //foreach //if($this->noteInfos['cosort']!='asc') krsort($tmplink); $unum = count($tmplink); - if($unum>0) - { + if ($unum > 0) { //echo "完成本次种子网址抓取,共找到:{$unum} 个记录!
\r\n"; - foreach($tmplink as $vs) - { + foreach ($tmplink as $vs) { $v = $vs[0]; $typeid = $vs[1]; - if($islisten==1) - { - $lrow = $this->dsql->GetOne("SELECT * FROM `#@__co_urls` WHERE nid='{$this->noteId}' AND hash='".md5($v['link'])."' "); - if(is_array($lrow)) - { + if ($islisten == 1) { + $lrow = $this->dsql->GetOne("SELECT * FROM `#@__co_urls` WHERE nid='{$this->noteId}' AND hash='" . md5($v['link']) . "' "); + if (is_array($lrow)) { continue; } } $inquery = "INSERT INTO `#@__co_htmls` (`nid` ,`typeid`, `title` , `litpic` , `url` , `dtime` , `isdown` , `isexport` , `result`) - VALUES ('{$this->noteId}' ,'$typeid', '".addslashes($v['title'])."' , '".addslashes($v['image'])."' , '".addslashes($v['link'])."' , '".time()."' , '0' , '0' , ''); "; + VALUES ('{$this->noteId}' ,'$typeid', '" . addslashes($v['title']) . "' , '" . addslashes($v['image']) . "' , '" . addslashes($v['link']) . "' , '" . time() . "' , '0' , '0' , ''); "; $this->dsql->ExecuteNoneQuery($inquery); - $inquery = "INSERT INTO `#@__co_urls`(hash,nid) VALUES ('".md5($v['link'])."','{$this->noteId}');"; + $inquery = "INSERT INTO `#@__co_urls`(hash,nid) VALUES ('" . md5($v['link']) . "','{$this->noteId}');"; $this->dsql->ExecuteNoneQuery($inquery); } - if($endpos >= $totallen) - { + if ($endpos >= $totallen) { return 0; + } else { + return ($totallen - $endpos); } - else - { - return ($totallen-$endpos); - } - } - else - { + } else { //仅在第一批采集时出错才返回 - if($glstart==0) - { + if ($glstart == 0) { return -1; } //在其它页出错照常采集后面内容 - if($endpos >= $totallen) - { + if ($endpos >= $totallen) { return 0; - } - else - { - return ($totallen-$endpos); + } else { + return ($totallen - $endpos); } } } @@ -1158,21 +977,19 @@ function GetSourceUrl($islisten=0, $glstart=0, $pagesize=10) * @param string $phpcode PHP代码 * @return string */ - function RunPHP($fvalue, $phpcode) + public function RunPHP($fvalue, $phpcode) { $DedeMeValue = $fvalue; $phpcode = preg_replace("#'@me'|\"@me\"|@me#isU", '$DedeMeValue', $phpcode); - if(preg_match("#@body#i", $phpcode)) - { + if (preg_match("#@body#i", $phpcode)) { $DedeBodyValue = $this->tmpHtml; $phpcode = preg_replace("#'@body'|\"@body\"|@body#isU", '$DedeBodyValue', $phpcode); } - if(preg_match("#@litpic#i", $phpcode)) - { + if (preg_match("#@litpic#i", $phpcode)) { $DedeLitPicValue = $this->breImage; $phpcode = preg_replace("#'@litpic'|\"@litpic\"|@litpic#isU", '$DedeLitPicValue', $phpcode); } - eval($phpcode.";"); + eval($phpcode . ";"); return $DedeMeValue; } @@ -1183,30 +1000,23 @@ function RunPHP($fvalue, $phpcode) * @param string $str 字符串 * @return string */ - function ChangeCode(&$str) + public function ChangeCode(&$str) { global $cfg_soft_lang; - if($cfg_soft_lang=='utf-8') - { - if($this->noteInfos["sourcelang"]=="gb2312") - { + if ($cfg_soft_lang == 'utf-8') { + if ($this->noteInfos["sourcelang"] == "gb2312") { $str = gb2utf8($str); } - if($this->noteInfos["sourcelang"]=="big5") - { + if ($this->noteInfos["sourcelang"] == "big5") { $str = gb2utf8(big52gb($str)); } - } - else - { - if($this->noteInfos["sourcelang"]=="utf-8") - { + } else { + if ($this->noteInfos["sourcelang"] == "utf-8") { $str = utf82gb($str); } - if($this->noteInfos["sourcelang"]=="big5") - { + if ($this->noteInfos["sourcelang"] == "big5") { $str = big52gb($str); } } } -}//End Class \ No newline at end of file +} //End Class diff --git a/include/dedecollection.func.php b/include/dedecollection.func.php index 3089a26f..a341f6f9 100755 --- a/include/dedecollection.func.php +++ b/include/dedecollection.func.php @@ -1,4 +1,4 @@ -100) - { + while (!feof($m_fp)) { + $line = trim(fgets($m_fp, 256)); + if ($line == "" || $lnum > 100) { break; } $hkey = ""; $hvalue = ""; $v = 0; - for($i=0; $i$maxtime) - { + if (time() - $starttime > $maxtime) { break; } //到达指定大小结束 - if($i >= $contentLength) - { + if ($i >= $contentLength) { break; } } - if($okdata!="") - { - fwrite($fp,$okdata); + if ($okdata != "") { + fwrite($fp, $okdata); } fclose($fp); - if($okdata=="") - { + if ($okdata == "") { @unlink($filename); fclose($m_fp); - return FALSE; + return false; } fclose($m_fp); - return TRUE; + return true; } /** @@ -160,18 +139,14 @@ function DownImageKeep($gurl, $rfurl, $filename, $gcookie="", $JumpCount=0, $max */ function RefurlCookie($gurl) { - global $gcookie,$lastRfurl; + global $gcookie, $lastRfurl; $gurl = trim($gurl); - if(!empty($gcookie) && $lastRfurl==$gurl) - { + if (!empty($gcookie) && $lastRfurl == $gurl) { return $gcookie; + } else { + $lastRfurl = $gurl; } - else - { - $lastRfurl=$gurl; - } - if(trim($gurl)=='') - { + if (trim($gurl) == '') { return ''; } $urlinfos = GetHostInfo($gurl); @@ -184,23 +159,18 @@ function RefurlCookie($gurl) $sessionQuery .= "Connection: Close\r\n\r\n"; $errno = ""; $errstr = ""; - $m_fp = fsockopen($ghost, 80, $errno, $errstr,10) or die($ghost.'
'); - fwrite($m_fp,$sessionQuery); + $m_fp = fsockopen($ghost, 80, $errno, $errstr, 10) or die($ghost . '
'); + fwrite($m_fp, $sessionQuery); $lnum = 0; //获取详细应答头 $gcookie = ""; - while(!feof($m_fp)) - { - $line = trim(fgets($m_fp,256)); - if($line == "" || $lnum>100) - { + while (!feof($m_fp)) { + $line = trim(fgets($m_fp, 256)); + if ($line == "" || $lnum > 100) { break; - } - else - { - if(preg_match("/^cookie/i", $line)) - { + } else { + if (preg_match("/^cookie/i", $line)) { $gcookie = $line; break; } @@ -221,7 +191,7 @@ function GetHostInfo($gurl) { $gurl = preg_replace("/^http:\/\//i", "", trim($gurl)); $garr['host'] = preg_replace("/\/(.*)$/i", "", $gurl); - $garr['query'] = "/".preg_replace("/^([^\/]*)\//i", "", $gurl); + $garr['query'] = "/" . preg_replace("/^([^\/]*)\//i", "", $gurl); return $garr; } @@ -234,31 +204,25 @@ function GetHostInfo($gurl) */ function TurnImageTag(&$body) { - global $cfg_album_width,$cfg_ddimg_width; - if(empty($cfg_album_width)) - { + global $cfg_album_width, $cfg_ddimg_width; + if (empty($cfg_album_width)) { $cfg_album_width = 800; } - if(empty($cfg_ddimg_width)) - { + if (empty($cfg_ddimg_width)) { $cfg_ddimg_width = 150; } $patten = "/<\\s*img\\s.*?src\\s*=\\s*([\"\\'])?(?(1)(.*?)\\1|([^\\s\\>\"\\']+))/isx"; - preg_match_all($patten,$body,$images); + preg_match_all($patten, $body, $images); $returnArray1 = $images[2]; $returnArray2 = $images[3]; - foreach ( $returnArray1 as $key => $value ) - { - if ($value) - { - $ttx .= "{dede:img ddimg='$litpicname' text='图 ".($key+1)."'}".$value."{/dede:img}"."\r\n"; - } - else - { - $ttx .= "{dede:img ddimg='$litpicname' text='图 ".($key+1)."'}".$returnArray2[$key]."{/dede:img}"."\r\n"; + foreach ($returnArray1 as $key => $value) { + if ($value) { + $ttx .= "{dede:img ddimg='$litpicname' text='图 " . ($key + 1) . "'}" . $value . "{/dede:img}" . "\r\n"; + } else { + $ttx .= "{dede:img ddimg='$litpicname' text='图 " . ($key + 1) . "'}" . $returnArray2[$key] . "{/dede:img}" . "\r\n"; } } - $ttx = "\r\n{dede:pagestyle maxwidth='{$cfg_album_width}' ddmaxwidth='{$cfg_ddimg_width}' row='3' col='3' value='2'/}\r\n{dede:comments}图集类型会采集时生成此配置是正常的,不过如果后面没有跟着img标记则表示规则无效{/dede:comments}\r\n".$ttx; + $ttx = "\r\n{dede:pagestyle maxwidth='{$cfg_album_width}' ddmaxwidth='{$cfg_ddimg_width}' row='3' col='3' value='2'/}\r\n{dede:comments}图集类型会采集时生成此配置是正常的,不过如果后面没有跟着img标记则表示规则无效{/dede:comments}\r\n" . $ttx; return $ttx; } @@ -273,15 +237,12 @@ function TurnLinkTag(&$body) { $ttx = ''; $handid = '服务器'; - preg_match_all("/]+?)>(.+?)<\/a>/is",$body,$match); - if(is_array($match[1]) && count($match[1])>0) - { - for($i=0;isset($match[1][$i]);$i++) - { - $servername = (isset($match[3][$i]) ? str_replace("'","`",$match[3][$i]) : $handid.($i+1)); - if(preg_match("/[<>]/", $servername) || strlen($servername)>40) - { - $servername = $handid.($i+1); + preg_match_all("/]+?)>(.+?)<\/a>/is", $body, $match); + if (is_array($match[1]) && count($match[1]) > 0) { + for ($i = 0;isset($match[1][$i]); $i++) { + $servername = (isset($match[3][$i]) ? str_replace("'", "`", $match[3][$i]) : $handid . ($i + 1)); + if (preg_match("/[<>]/", $servername) || strlen($servername) > 40) { + $servername = $handid . ($i + 1); } $ttx .= "{dede:link text='$servername'} {$match[1][$i]} {/dede:link}\r\n"; } @@ -300,7 +261,7 @@ function RpCdata($str) { $str = str_replace('', '', $str); - return $str; + return $str; } /** @@ -318,63 +279,43 @@ function GetRssLinks($rssurl) $rsshtml = $dhd->GetHtml(); //分析编码 - preg_match("/encoding=[\"']([^\"']*)[\"']/is",$rsshtml,$infos); - if(isset($infos[1])) - { + preg_match("/encoding=[\"']([^\"']*)[\"']/is", $rsshtml, $infos); + if (isset($infos[1])) { $pcode = strtolower(trim($infos[1])); - } - else - { + } else { $pcode = strtolower($cfg_soft_lang); } - if($cfg_soft_lang=='gb2312') - { - if($pcode=='utf-8') - { + if ($cfg_soft_lang == 'gb2312') { + if ($pcode == 'utf-8') { $rsshtml = utf82gb($rsshtml); - } - else if($pcode=='big5') - { + } else if ($pcode == 'big5') { $rsshtml = big52gb($rsshtml); } - } - else if($cfg_soft_lang=='utf-8') - { - if($pcode=='gbk'||$pcode=='gb2312') - { + } else if ($cfg_soft_lang == 'utf-8') { + if ($pcode == 'gbk' || $pcode == 'gb2312') { $rsshtml = gb2utf8($rsshtml); - } - else if($pcode=='big5') - { + } else if ($pcode == 'big5') { $rsshtml = gb2utf8(big52gb($rsshtml)); } } $rsarr = array(); - preg_match_all("/(.*)<\/title>/isU",$rsshtml,$titles); - preg_match_all("/(.*)<\/link>/isU",$rsshtml,$links); - preg_match_all("/(.*)<\/description>/isU",$rsshtml,$descriptions); - if(!isset($links[2])) - { + preg_match_all("/(.*)<\/title>/isU", $rsshtml, $titles); + preg_match_all("/(.*)<\/link>/isU", $rsshtml, $links); + preg_match_all("/(.*)<\/description>/isU", $rsshtml, $descriptions); + if (!isset($links[2])) { return ''; } - foreach($links[2] as $k=>$v) - { + foreach ($links[2] as $k => $v) { $rsarr[$k]['link'] = RpCdata($v); - if(isset($titles[2][$k])) - { + if (isset($titles[2][$k])) { $rsarr[$k]['title'] = RpCdata($titles[2][$k]); - } - else - { + } else { $rsarr[$k]['title'] = preg_replace("/^(.*)\//i", "", RpCdata($titles[2][$k])); } - if(isset($descriptions[2][$k])) - { - $rsarr[$k]['image'] = GetddImgFromRss($descriptions[2][$k],$rssurl); - } - else - { + if (isset($descriptions[2][$k])) { + $rsarr[$k]['image'] = GetddImgFromRss($descriptions[2][$k], $rssurl); + } else { $rsarr[$k]['image'] = ''; } } @@ -389,21 +330,17 @@ function GetRssLinks($rssurl) * @param string $refurl 来源地址 * @return string */ -function GetddImgFromRss($descriptions,$refurl) +function GetddImgFromRss($descriptions, $refurl) { - if($descriptions=='') - { + if ($descriptions == '') { return ''; } - preg_match_all("/ \r\n\t]{1,}/isU",$descriptions,$imgs); - if(isset($imgs[2][0])) - { + preg_match_all("/ \r\n\t]{1,}/isU", $descriptions, $imgs); + if (isset($imgs[2][0])) { $imgs[2][0] = preg_replace("/[\"']/", '', $imgs[2][0]); $imgs[2][0] = preg_replace("/\/{1,}/", '/', $imgs[2][0]); - return FillUrl($refurl,$imgs[2][0]); - } - else - { + return FillUrl($refurl, $imgs[2][0]); + } else { return ''; } } @@ -416,75 +353,59 @@ function GetddImgFromRss($descriptions,$refurl) * @param string $surl 站点地址 * @return string */ -function FillUrl($refurl,$surl) +function FillUrl($refurl, $surl) { $i = $pathStep = 0; $dstr = $pstr = $okurl = ''; $refurl = trim($refurl); $surl = trim($surl); $urls = @parse_url($refurl); - $basehost = ( (!isset($urls['port']) || $urls['port']=='80') ? $urls['host'] : $urls['host'].':'.$urls['port']); + $basehost = ((!isset($urls['port']) || $urls['port'] == '80') ? $urls['host'] : $urls['host'] . ':' . $urls['port']); //$basepath = $basehost.(!isset($urls['path']) ? '' : '/'.$urls['path']); //由于直接获得的path在处理 http://xxxx/nnn/aaa?fdsafd 这种情况时会有错误,因此用其它方式处理 $basepath = $basehost; - $paths = explode('/',preg_replace("/^http:\/\//i", "", $refurl)); + $paths = explode('/', preg_replace("/^http:\/\//i", "", $refurl)); $n = count($paths); - for($i=1;$i < ($n-1);$i++) - { - if(!preg_match("/[\?]/", $paths[$i])) $basepath .= '/'.$paths[$i]; + for ($i = 1; $i < ($n - 1); $i++) { + if (!preg_match("/[\?]/", $paths[$i])) { + $basepath .= '/' . $paths[$i]; + } + } - if(!preg_match("/[\?\.]/", $paths[$n-1])) - { - $basepath .= '/'.$paths[$n-1]; + if (!preg_match("/[\?\.]/", $paths[$n - 1])) { + $basepath .= '/' . $paths[$n - 1]; } - if($surl=='') - { + if ($surl == '') { return $basepath; } $pos = strpos($surl, "#"); - if($pos>0) - { + if ($pos > 0) { $surl = substr($surl, 0, $pos); } //用 '/' 表示网站根的网址 - if($surl[0]=='/') - { - $okurl = $basehost.$surl; - } - else if($surl[0]=='.') - { - if(strlen($surl)<=2) - { + if ($surl[0] == '/') { + $okurl = $basehost . $surl; + } else if ($surl[0] == '.') { + if (strlen($surl) <= 2) { return ''; + } else if ($surl[1] == '/') { + $okurl = $basepath . preg_replace('/^./', '', $surl); + } else { + $okurl = $basepath . '/' . $surl; } - else if($surl[1]=='/') - { - $okurl = $basepath.preg_replace('/^./', '', $surl); - } - else - { - $okurl = $basepath.'/'.$surl; - } - } - else - { - if( strlen($surl) < 7 ) - { - $okurl = $basepath.'/'.$surl; - } - else if( preg_match("/^http:\/\//i",$surl) ) - { + } else { + if (strlen($surl) < 7) { + $okurl = $basepath . '/' . $surl; + } else if (preg_match("/^http:\/\//i", $surl)) { $okurl = $surl; - } - else - { - $okurl = $basepath.'/'.$surl; + } else { + $okurl = $basepath . '/' . $surl; } } $okurl = preg_replace("/^http:\/\//i", '', $okurl); - $okurl = 'http://'.preg_replace("/\/{1,}/", '/', $okurl); + $okurl = 'http://' . preg_replace("/\/{1,}/", '/', $okurl); return $okurl; } @@ -501,58 +422,46 @@ function FillUrl($refurl,$surl) * @param string $batchrule 列表规则 * @return string */ -function GetUrlFromListRule($regxurl='',$handurl='',$startid=0,$endid=0,$addv=1,$usemore=0,$batchrule='') +function GetUrlFromListRule($regxurl = '', $handurl = '', $startid = 0, $endid = 0, $addv = 1, $usemore = 0, $batchrule = '') { - global $dsql,$islisten; + global $dsql, $islisten; $lists = array(); $n = 0; $islisten = (empty($islisten) ? 0 : $islisten); - if($handurl!='') - { - $handurls = explode("\n",$handurl); - foreach($handurls as $handurl) - { + if ($handurl != '') { + $handurls = explode("\n", $handurl); + foreach ($handurls as $handurl) { $handurl = trim($handurl); - if(preg_match("/^http:\/\//i", $handurl)) - { + if (preg_match("/^http:\/\//i", $handurl)) { $lists[$n][0] = $handurl; $lists[$n][1] = 0; $n++; - if($islisten==1) - { + if ($islisten == 1) { break; } } } } - if($regxurl!='') - { + if ($regxurl != '') { //没指定(#)和(*) - if(!preg_match("/\(\*\)/i", $regxurl) && !preg_match("/\(#\)/", $regxurl)) - { + if (!preg_match("/\(\*\)/i", $regxurl) && !preg_match("/\(#\)/", $regxurl)) { $lists[$n][0] = $regxurl; $lists[$n][1] = 0; $n++; - } - else - { - if($addv <= 0) - { + } else { + if ($addv <= 0) { $addv = 1; } //没指定多栏目匹配规则 - if($usemore==0) - { - while($startid <= $endid) - { - $lists[$n][0] = str_replace("(*)",sprintf('%0'.strlen($startid).'d',$startid),$regxurl); + if ($usemore == 0) { + while ($startid <= $endid) { + $lists[$n][0] = str_replace("(*)", sprintf('%0' . strlen($startid) . 'd', $startid), $regxurl); $lists[$n][1] = 0; - $startid = sprintf('%0'.strlen($startid).'d',$startid + $addv); + $startid = sprintf('%0' . strlen($startid) . 'd', $startid + $addv); $n++; - if($n>2000 || $islisten==1) - { + if ($n > 2000 || $islisten == 1) { break; } } @@ -560,16 +469,13 @@ function GetUrlFromListRule($regxurl='',$handurl='',$startid=0,$endid=0,$addv=1, //匹配多个栏目 //规则表达式 [(#)=>(#)匹配的网址; (*)=>(*)的范围,如:1-20; typeid=>栏目id; addurl=>附加的网址(用|分开多个)] - else - { - $nrules = explode(']',trim($batchrule)); - foreach($nrules as $nrule) - { + else { + $nrules = explode(']', trim($batchrule)); + foreach ($nrules as $nrule) { $nrule = trim($nrule); $nrule = preg_replace("/^\[|\]$/", '', $nrule); - $nrules = explode(';',$nrule); - if(count($nrules)<3) - { + $nrules = explode(';', $nrule); + if (count($nrules) < 3) { continue; } $brtag = ''; @@ -577,83 +483,63 @@ function GetUrlFromListRule($regxurl='',$handurl='',$startid=0,$endid=0,$addv=1, $endid = 0; $typeid = 0; $addurls = array(); - foreach($nrules as $nrule) - { + foreach ($nrules as $nrule) { $nrule = trim($nrule); - list($k,$v) = explode('=>',$nrule); - if(trim($k)=='(#)') - { + list($k, $v) = explode('=>', $nrule); + if (trim($k) == '(#)') { $brtag = trim($v); - } - else if(trim($k)=='typeid') - { + } else if (trim($k) == 'typeid') { $typeid = trim($v); - } - else if(trim($k)=='addurl') - { + } else if (trim($k) == 'addurl') { $addurl = trim($v); - $addurls = explode('|',$addurl); - } - else if(trim($k)=='(*)') - { + $addurls = explode('|', $addurl); + } else if (trim($k) == '(*)') { $v = preg_replace("/[ \r\n\t]/", '', trim($v)); - list($startid,$endid) = explode('-',$v); + list($startid, $endid) = explode('-', $v); } } //如果栏目用栏目名称 - if(preg_match('/[^0-9]/', $typeid)) - { + if (preg_match('/[^0-9]/', $typeid)) { $arr = $dsql->GetOne("SELECT id FROM `#@__arctype` WHERE typename LIKE '$typeid' "); - if(is_array($arr)) - { + if (is_array($arr)) { $typeid = $arr['id']; - } - else - { + } else { $typeid = 0; } } //附加网址优先 $mjj = 0; - if(isset($addurls[0])) - { - foreach($addurls as $addurl) - { + if (isset($addurls[0])) { + foreach ($addurls as $addurl) { $addurl = trim($addurl); - if($addurl=='') - { + if ($addurl == '') { continue; } $lists[$n][0] = $addurl; $lists[$n][1] = $typeid; $n++; $mjj++; - if($islisten==1) - { + if ($islisten == 1) { break; } } } //如果为非监听模式或监听模式没手工指定的附加网址 - if($islisten!=1 || $mjj==0 ) - { + if ($islisten != 1 || $mjj == 0) { //匹配规则里的网址,注:(#)的网址是是允许使用(*)的 - while($startid <= $endid) - { - $lists[$n][0] = str_replace("(#)",$brtag,$regxurl); - $lists[$n][0] = str_replace("(*)",sprintf('%0'.strlen($startid).'d',$startid),$lists[$n][0]); + while ($startid <= $endid) { + $lists[$n][0] = str_replace("(#)", $brtag, $regxurl); + $lists[$n][0] = str_replace("(*)", sprintf('%0' . strlen($startid) . 'd', $startid), $lists[$n][0]); $lists[$n][1] = $typeid; - $startid = sprintf('%0'.strlen($startid).'d',$startid + $addv); + $startid = sprintf('%0' . strlen($startid) . 'd', $startid + $addv); $n++; - if($islisten==1) - { + if ($islisten == 1) { break; } - if($n>20000) - { + if ($n > 20000) { break; } } @@ -666,4 +552,4 @@ function GetUrlFromListRule($regxurl='',$handurl='',$startid=0,$endid=0,$addv=1, } return $lists; -}//End \ No newline at end of file +} //End diff --git a/include/downmix.inc.php b/include/downmix.inc.php index b395c631..16c11651 100755 --- a/include/downmix.inc.php +++ b/include/downmix.inc.php @@ -1,4 +1,4 @@ -GetOne("SELECT arc.*,ch.maintable,ch.addtable,ch.issystem FROM `#@__arctiny` arc LEFT JOIN `#@__channeltype` ch ON ch.id=arc.channel WHERE arc.id='$aid' "); - if(!is_array($chRow)) { + if (!is_array($chRow)) { return $reArr; - } - else { - if(empty($chRow['maintable'])) $chRow['maintable'] = '#@__archives'; + } else { + if (empty($chRow['maintable'])) { + $chRow['maintable'] = '#@__archives'; + } + } - if($chRow['issystem']!=-1) - { + if ($chRow['issystem'] != -1) { $nquery = " SELECT arc.*,tp.typedir,tp.topid,tp.namerule,tp.moresite,tp.siteurl,tp.sitepath FROM `{$chRow['maintable']}` arc LEFT JOIN `#@__arctype` tp ON tp.id=arc.typeid WHERE arc.id='$aid' "; - } - else - { + } else { $nquery = " SELECT arc.*,1 AS ismake,0 AS money,'' AS filename,tp.typedir,tp.topid,tp.namerule,tp.moresite,tp.siteurl,tp.sitepath FROM `{$chRow['addtable']}` arc LEFT JOIN `#@__arctype` tp ON tp.id=arc.typeid WHERE arc.aid='$aid' "; @@ -48,40 +46,39 @@ function GetOneArchive($aid) $arcRow = $dsql->GetOne($nquery); - if(!is_array($arcRow)) { + if (!is_array($arcRow)) { return $reArr; } - if(!isset($arcRow['description'])) { + if (!isset($arcRow['description'])) { $arcRow['description'] = ''; } - if(empty($arcRow['description']) && isset($arcRow['body'])) { + if (empty($arcRow['description']) && isset($arcRow['body'])) { $arcRow['description'] = cn_substr(html2text($arcRow['body']), 250); } - if(!isset($arcRow['pubdate'])) { + if (!isset($arcRow['pubdate'])) { $arcRow['pubdate'] = $arcRow['senddate']; } - if(!isset($arcRow['notpost'])) { + if (!isset($arcRow['notpost'])) { $arcRow['notpost'] = 0; } $reArr = $arcRow; - $reArr['aid'] = $aid; - $reArr['topid'] = $arcRow['topid']; + $reArr['aid'] = $aid; + $reArr['topid'] = $arcRow['topid']; $reArr['arctitle'] = $arcRow['title']; $reArr['arcurl'] = GetFileUrl($aid, $arcRow['typeid'], $arcRow['senddate'], $reArr['title'], - $arcRow['ismake'], $arcRow['arcrank'], $arcRow['namerule'], $arcRow['typedir'], - $arcRow['money'], $arcRow['filename'], $arcRow['moresite'], $arcRow['siteurl'], - $arcRow['sitepath']); + $arcRow['ismake'], $arcRow['arcrank'], $arcRow['namerule'], $arcRow['typedir'], + $arcRow['money'], $arcRow['filename'], $arcRow['moresite'], $arcRow['siteurl'], + $arcRow['sitepath']); return $reArr; } } - /** * 获取模型的表信息 * @@ -89,21 +86,15 @@ function GetOneArchive($aid) * @param string $formtype 表单类型 * @return array */ -if ( ! function_exists('GetChannelTable')) -{ - function GetChannelTable($id,$formtype='channel') +if (!function_exists('GetChannelTable')) { + function GetChannelTable($id, $formtype = 'channel') { global $dsql; - if($formtype == 'archive') - { + if ($formtype == 'archive') { $query = "SELECT ch.maintable, ch.addtable FROM #@__arctiny tin LEFT JOIN #@__channeltype ch ON ch.id=tin.channel WHERE tin.id='$id'"; - } - else if($formtype == 'typeid') - { + } else if ($formtype == 'typeid') { $query = "SELECT ch.maintable, ch.addtable FROM #@__arctype act LEFT JOIN #@__channeltype ch ON ch.id=act.channeltype WHERE act.id='$id'"; - } - else - { + } else { $query = "SELECT maintable, addtable FROM #@__channeltype WHERE id='$id'"; } $row = $dsql->GetOne($query); @@ -117,17 +108,15 @@ function GetChannelTable($id,$formtype='channel') * @param int $aid 文档id * @return string */ -if ( ! function_exists('GetTags')) -{ +if (!function_exists('GetTags')) { function GetTags($aid) { global $dsql; $tags = ''; $query = "SELECT tag FROM `#@__taglist` WHERE aid='$aid' "; - $dsql->Execute('tag',$query); - while($row = $dsql->GetArray('tag')) - { - $tags .= ($tags=='' ? $row['tag'] : ','.$row['tag']); + $dsql->Execute('tag', $query); + while ($row = $dsql->GetArray('tag')) { + $tags .= ($tags == '' ? $row['tag'] : ',' . $row['tag']); } return $tags; } @@ -145,16 +134,24 @@ function GetTags($aid) * @param int $mid 会员ID * @return int */ -if ( ! function_exists('GetIndexKey')) -{ - function GetIndexKey($arcrank, $typeid, $sortrank=0, $channelid=1, $senddate=0, $mid=1) +if (!function_exists('GetIndexKey')) { + function GetIndexKey($arcrank, $typeid, $sortrank = 0, $channelid = 1, $senddate = 0, $mid = 1) { - global $dsql,$senddate,$typeid2; - if(empty($typeid2)) $typeid2 = 0; - if(empty($senddate)) $senddate = time(); - if(empty($sortrank)) $sortrank = $senddate; - $typeid2 = intval($typeid2); - $senddate = intval($senddate); + global $dsql, $senddate, $typeid2; + if (empty($typeid2)) { + $typeid2 = 0; + } + + if (empty($senddate)) { + $senddate = time(); + } + + if (empty($sortrank)) { + $sortrank = $senddate; + } + + $typeid2 = intval($typeid2); + $senddate = intval($senddate); $iquery = " INSERT INTO `#@__arctiny` (`arcrank`,`typeid`,`typeid2`,`channel`,`senddate`, `sortrank`, `mid`) VALUES ('$arcrank','$typeid','$typeid2' , '$channelid','$senddate', '$sortrank', '$mid') "; @@ -164,7 +161,6 @@ function GetIndexKey($arcrank, $typeid, $sortrank=0, $channelid=1, $senddate=0, } } - /** * 更新微表key及Tag * @@ -176,45 +172,39 @@ function GetIndexKey($arcrank, $typeid, $sortrank=0, $channelid=1, $senddate=0, * @param string $tags tag标签 * @return string */ -if ( ! function_exists('UpIndexKey')) -{ - function UpIndexKey($id, $arcrank, $typeid, $sortrank=0, $tags='') +if (!function_exists('UpIndexKey')) { + function UpIndexKey($id, $arcrank, $typeid, $sortrank = 0, $tags = '') { - global $dsql,$typeid2; - if(empty($typeid2)) $typeid2 = 0; + global $dsql, $typeid2; + if (empty($typeid2)) { + $typeid2 = 0; + } + $addtime = time(); $query = " UPDATE `#@__arctiny` SET `arcrank`='$arcrank', `typeid`='$typeid', `typeid2`='$typeid2', `sortrank`='$sortrank' WHERE id = '$id' "; $dsql->ExecuteNoneQuery($query); /* - * 处理修改后的Tag - */ - if($tags!='') - { + * 处理修改后的Tag + */ + if ($tags != '') { $oldtag = GetTags($id); - $oldtags = explode(',',$oldtag); - $tagss = explode(',',$tags); - foreach($tagss as $tag) - { + $oldtags = explode(',', $oldtag); + $tagss = explode(',', $tags); + foreach ($tagss as $tag) { $tag = trim($tag); - if(isset($tag[12]) || $tag!=stripslashes($tag)) - { + if (isset($tag[12]) || $tag != stripslashes($tag)) { continue; } - if(!in_array($tag,$oldtags)) - { - InsertOneTag($tag,$id); + if (!in_array($tag, $oldtags)) { + InsertOneTag($tag, $id); } } - foreach($oldtags as $tag) - { - if(!in_array($tag,$tagss)) - { + foreach ($oldtags as $tag) { + if (!in_array($tag, $tagss)) { $dsql->ExecuteNoneQuery("DELETE FROM `#@__taglist` WHERE aid='$id' AND tag LIKE '$tag' "); $dsql->ExecuteNoneQuery("UPDATE `#@__tagindex` SET total=total-1 WHERE tag LIKE '$tag' "); - } - else - { + } else { $dsql->ExecuteNoneQuery("UPDATE `#@__taglist` SET `arcrank` = '$arcrank', `typeid` = '$typeid' WHERE tag LIKE '$tag' "); } } @@ -222,7 +212,6 @@ function UpIndexKey($id, $arcrank, $typeid, $sortrank=0, $tags='') } } - /** * 插入Tags * @@ -231,24 +220,20 @@ function UpIndexKey($id, $arcrank, $typeid, $sortrank=0, $tags='') * @param int $aid 文档AID * @return void */ -if ( ! function_exists('InsertTags')) -{ +if (!function_exists('InsertTags')) { function InsertTags($tag, $aid) { - $tags = explode(',',$tag); - foreach($tags as $tag) - { + $tags = explode(',', $tag); + foreach ($tags as $tag) { $tag = trim($tag); - if(isset($tag[20]) || $tag!=stripslashes($tag)) - { + if (isset($tag[20]) || $tag != stripslashes($tag)) { continue; } - InsertOneTag($tag,$aid); + InsertOneTag($tag, $aid); } } } - /** * 插入一个tag * @@ -257,40 +242,32 @@ function InsertTags($tag, $aid) * @param int $aid 文档AID * @return void */ -if ( ! function_exists('InsertOneTag')) -{ +if (!function_exists('InsertOneTag')) { function InsertOneTag($tag, $aid) { - global $typeid,$arcrank,$dsql; + global $typeid, $arcrank, $dsql; $tag = trim($tag); - if($tag == '') - { + if ($tag == '') { return ''; } - if(empty($typeid)) - { + if (empty($typeid)) { $typeid = 0; } - if(empty($arcrank)) - { + if (empty($arcrank)) { $arcrank = 0; } $rs = false; $addtime = time(); $row = $dsql->GetOne("SELECT * FROM `#@__tagindex` WHERE tag LIKE '$tag' "); - if(!is_array($row)) - { + if (!is_array($row)) { $rs = $dsql->ExecuteNoneQuery(" INSERT INTO `#@__tagindex`(`tag`,`typeid`,`count`,`total`,`weekcc`,`monthcc`,`weekup`,`monthup`,`addtime`) VALUES('$tag','$typeid','0','1','0','0','$addtime','$addtime','$addtime'); "); $tid = $dsql->GetLastID(); - } - else - { + } else { $rs = $dsql->ExecuteNoneQuery(" UPDATE `#@__tagindex` SET total=total+1,addtime=$addtime WHERE tag LIKE '$tag' "); $tid = $row['id']; } - if($rs) - { + if ($rs) { $dsql->ExecuteNoneQuery("INSERT INTO `#@__taglist`(`tid`,`aid`,`arcrank`,`typeid` , `tag`) VALUES('$tid','$aid','$arcrank','$typeid' , '$tag'); "); } } -} \ No newline at end of file +} diff --git a/include/helpers/cache.helper.php b/include/helpers/cache.helper.php index 3142ed6a..f738d1df 100755 --- a/include/helpers/cache.helper.php +++ b/include/helpers/cache.helper.php @@ -1,4 +1,4 @@ -connect ( $mc_path ['host'], $mc_path ['port'] ); + if ($is_memcache === true && !empty($cache_helper_config['memcache']) && $cache_helper_config['memcache']['is_mc_enable'] === 'Y') { + $mc_path = empty($cache_helper_config['memcache']['mc'][substr($key, 0, 1)]) ? $cache_helper_config['memcache']['mc']['default'] : $cache_helper_config['memcache']['mc'][substr($key, 0, 1)]; + $mc_path = parse_url($mc_path); + $key = ltrim($mc_path['path'], '/') . '_' . $prefix . '_' . $key; + if (empty($GLOBALS['mc_' . $mc_path['host']])) { + $GLOBALS['mc_' . $mc_path['host']] = new Memcache(); + $GLOBALS['mc_' . $mc_path['host']]->connect($mc_path['host'], $mc_path['port']); } - return $GLOBALS ['mc_' . $mc_path ['host']]->get ( $key ); + return $GLOBALS['mc_' . $mc_path['host']]->get($key); } - $key = substr ( $key, 0, 2 ) . '/' . substr ( $key, 2, 2 ) . '/' . substr ( $key, 4, 2 ) . '/' . $key; - $result = @file_get_contents ( DEDEDATA . "/cache/$prefix/$key.php" ); - - if ($result === false) - { + $key = substr($key, 0, 2) . '/' . substr($key, 2, 2) . '/' . substr($key, 4, 2) . '/' . $key; + $result = @file_get_contents(DEDEDATA . "/cache/$prefix/$key.php"); + + if ($result === false) { return false; } $result = str_replace("\n\r", "", $result); - $result = @unserialize ( $result ); - if($result ['timeout'] != 0 && $result ['timeout'] < time ()) - { - return false; + $result = @unserialize($result); + if ($result['timeout'] != 0 && $result['timeout'] < time()) { + return false; } - return $result ['data']; + return $result['data']; } } - /** * 写缓存 * @@ -64,37 +58,33 @@ function GetCache($prefix, $key, $is_memcache = TRUE) * @param string $timeout 缓存时间 * @return int */ -if ( ! function_exists('SetCache')) -{ - function SetCache($prefix, $key, $value, $timeout = 3600, $is_memcache = TRUE) +if (!function_exists('SetCache')) { + function SetCache($prefix, $key, $value, $timeout = 3600, $is_memcache = true) { global $cache_helper_config; - $key = md5 ( $key ); + $key = md5($key); /* 如果启用MC缓存 */ - if (! empty ( $cache_helper_config['memcache'] ) && $cache_helper_config['memcache'] ['is_mc_enable'] === 'Y' && $is_memcache === TRUE) - { - $mc_path = empty ( $cache_helper_config['memcache'] ['mc'] [substr ( $key, 0, 1 )] ) ? $cache_helper_config['memcache'] ['mc'] ['default'] : $cache_helper_config['memcache'] ['mc'] [substr ( $key, 0, 1 )]; - $mc_path = parse_url ( $mc_path ); - $key = ltrim ( $mc_path ['path'], '/' ) . '_' . $prefix . '_' . $key; - if (empty ( $GLOBALS ['mc_' . $mc_path ['host']] )) - { - $GLOBALS ['mc_' . $mc_path ['host']] = new Memcache ( ); - $GLOBALS ['mc_' . $mc_path ['host']]->connect ( $mc_path ['host'], $mc_path ['port'] ); + if (!empty($cache_helper_config['memcache']) && $cache_helper_config['memcache']['is_mc_enable'] === 'Y' && $is_memcache === true) { + $mc_path = empty($cache_helper_config['memcache']['mc'][substr($key, 0, 1)]) ? $cache_helper_config['memcache']['mc']['default'] : $cache_helper_config['memcache']['mc'][substr($key, 0, 1)]; + $mc_path = parse_url($mc_path); + $key = ltrim($mc_path['path'], '/') . '_' . $prefix . '_' . $key; + if (empty($GLOBALS['mc_' . $mc_path['host']])) { + $GLOBALS['mc_' . $mc_path['host']] = new Memcache(); + $GLOBALS['mc_' . $mc_path['host']]->connect($mc_path['host'], $mc_path['port']); //设置数据压缩门槛 //$GLOBALS ['mc_' . $mc_path ['host']]->setCompressThreshold(2048, 0.2); } - $result = $GLOBALS ['mc_' . $mc_path ['host']]->set ( $key, $value, MEMCACHE_COMPRESSED, $timeout ); + $result = $GLOBALS['mc_' . $mc_path['host']]->set($key, $value, MEMCACHE_COMPRESSED, $timeout); return $result; } - $key = substr ( $key, 0, 2 ) . '/' . substr ( $key, 2, 2 ) . '/' . substr ( $key, 4, 2 ) . '/' . $key; - $tmp ['data'] = $value; - $tmp ['timeout'] = $timeout != 0 ? time () + ( int ) $timeout : 0; - $cache_data = "\n\r".@serialize ( $tmp ); - return @PutFile ( DEDEDATA . "/cache/$prefix/$key.php", $cache_data); + $key = substr($key, 0, 2) . '/' . substr($key, 2, 2) . '/' . substr($key, 4, 2) . '/' . $key; + $tmp['data'] = $value; + $tmp['timeout'] = $timeout != 0 ? time() + (int) $timeout : 0; + $cache_data = "\n\r" . @serialize($tmp); + return @PutFile(DEDEDATA . "/cache/$prefix/$key.php", $cache_data); } } - /** * 删除缓存 * @@ -104,27 +94,24 @@ function SetCache($prefix, $key, $value, $timeout = 3600, $is_memcache = TRUE) * @param string $is_memcache 是否为memcache缓存 * @return string */ -if ( ! function_exists('DelCache')) -{ +if (!function_exists('DelCache')) { /* 删缓存 */ - function DelCache($prefix, $key, $is_memcache = TRUE) + function DelCache($prefix, $key, $is_memcache = true) { global $cache_helper_config; - $key = md5 ( $key ); + $key = md5($key); /* 如果启用MC缓存 */ - if (! empty ( $cache_helper_config['memcache'] ) && $cache_helper_config['memcache'] ['is_mc_enable'] === TRUE && $is_memcache === TRUE) - { - $mc_path = empty ( $cache_helper_config['memcache'] ['mc'] [substr ( $key, 0, 1 )] ) ? $cache_helper_config['memcache'] ['mc'] ['default'] : $cache_helper_config['memcache'] ['mc'] [substr ( $key, 0, 1 )]; - $mc_path = parse_url ( $mc_path ); - $key = ltrim ( $mc_path ['path'], '/' ) . '_' . $prefix . '_' . $key; - if (empty ( $GLOBALS ['mc_' . $mc_path ['host']] )) - { - $GLOBALS ['mc_' . $mc_path ['host']] = new Memcache ( ); - $GLOBALS ['mc_' . $mc_path ['host']]->connect ( $mc_path ['host'], $mc_path ['port'] ); + if (!empty($cache_helper_config['memcache']) && $cache_helper_config['memcache']['is_mc_enable'] === true && $is_memcache === true) { + $mc_path = empty($cache_helper_config['memcache']['mc'][substr($key, 0, 1)]) ? $cache_helper_config['memcache']['mc']['default'] : $cache_helper_config['memcache']['mc'][substr($key, 0, 1)]; + $mc_path = parse_url($mc_path); + $key = ltrim($mc_path['path'], '/') . '_' . $prefix . '_' . $key; + if (empty($GLOBALS['mc_' . $mc_path['host']])) { + $GLOBALS['mc_' . $mc_path['host']] = new Memcache(); + $GLOBALS['mc_' . $mc_path['host']]->connect($mc_path['host'], $mc_path['port']); } - return $GLOBALS ['mc_' . $mc_path ['host']]->delete ( $key ); + return $GLOBALS['mc_' . $mc_path['host']]->delete($key); } - $key = substr ( $key, 0, 2 ) . '/' . substr ( $key, 2, 2 ) . '/' . substr ( $key, 4, 2 ) . '/' . $key; - return @unlink ( DEDEDATA . "/cache/$prefix/$key.php" ); + $key = substr($key, 0, 2) . '/' . substr($key, 2, 2) . '/' . substr($key, 4, 2) . '/' . $key; + return @unlink(DEDEDATA . "/cache/$prefix/$key.php"); } -} \ No newline at end of file +} diff --git a/include/helpers/channelunit.helper.php b/include/helpers/channelunit.helper.php index 7b159ffc..2070b1ef 100755 --- a/include/helpers/channelunit.helper.php +++ b/include/helpers/channelunit.helper.php @@ -1,4 +1,4 @@ -=0;$i--) - { - if($articlename[$i]=='/') - { + + $slen = strlen($articlename) - 1; + for ($i = $slen; $i >= 0; $i--) { + if ($articlename[$i] == '/') { $subpos = $i; break; } } - $okdir = substr($articlename,0,$subpos); + $okdir = substr($articlename, 0, $subpos); CreateDir($okdir); return $articlename; } } - - /** * 获得文件相对于主站点根目录的物理文件名(动态网址返回url) * @@ -146,57 +130,45 @@ function GetFileNewName($aid,$typeid,$timetag,$title,$ismake=0,$rank=0,$namerule * @param string $filename 文件名称 * @return string */ -if ( ! function_exists('GetFileName')) -{ - function GetFileName($aid,$typeid,$timetag,$title,$ismake=0,$rank=0,$namerule='',$typedir='',$money=0,$filename='') +if (!function_exists('GetFileName')) { + function GetFileName($aid, $typeid, $timetag, $title, $ismake = 0, $rank = 0, $namerule = '', $typedir = '', $money = 0, $filename = '') { global $cfg_rewrite, $cfg_cmspath, $cfg_arcdir, $cfg_special, $cfg_arc_dirname; //没指定栏目时用固定规则(专题) - if(empty($namerule)) { - $namerule = $cfg_special.'/arc-{aid}.html'; + if (empty($namerule)) { + $namerule = $cfg_special . '/arc-{aid}.html'; $typeid = -1; } - if($rank!=0 || $ismake==-1 || $typeid==0 || $money>0) - { + if ($rank != 0 || $ismake == -1 || $typeid == 0 || $money > 0) { //动态文章 - if($cfg_rewrite == 'Y') - { - return $GLOBALS["cfg_plus_dir"]."/view-".$aid.'-1.html'; + if ($cfg_rewrite == 'Y') { + return $GLOBALS["cfg_plus_dir"] . "/view-" . $aid . '-1.html'; + } else { + return $GLOBALS['cfg_phpurl'] . "/view.php?aid=$aid"; } - else - { - return $GLOBALS['cfg_phpurl']."/view.php?aid=$aid"; - } - } - else - { + } else { $articleDir = MfTypedir($typedir); $articleRule = strtolower($namerule); - if($articleRule=='') - { + if ($articleRule == '') { $articleRule = strtolower($GLOBALS['cfg_df_namerule']); } - if($typedir=='') - { - $articleDir = $GLOBALS['cfg_cmspath'].$GLOBALS['cfg_arcdir']; + if ($typedir == '') { + $articleDir = $GLOBALS['cfg_cmspath'] . $GLOBALS['cfg_arcdir']; } $dtime = GetDateMk($timetag); list($y, $m, $d) = explode('-', $dtime); - $arr_rpsource = array('{typedir}','{y}','{m}','{d}','{timestamp}','{aid}','{cc}'); - $arr_rpvalues = array($articleDir,$y, $m, $d, $timetag, $aid, dd2char($m.$d.$aid.$y)); - if($filename != '') - { - $articleRule = dirname($articleRule).'/'.$filename.$GLOBALS['cfg_df_ext']; + $arr_rpsource = array('{typedir}', '{y}', '{m}', '{d}', '{timestamp}', '{aid}', '{cc}'); + $arr_rpvalues = array($articleDir, $y, $m, $d, $timetag, $aid, dd2char($m . $d . $aid . $y)); + if ($filename != '') { + $articleRule = dirname($articleRule) . '/' . $filename . $GLOBALS['cfg_df_ext']; } - $articleRule = str_replace($arr_rpsource,$arr_rpvalues,$articleRule); - if(preg_match("/\{p/", $articleRule)) - { - $articleRule = str_replace('{pinyin}',GetPinyin($title).'_'.$aid,$articleRule); - $articleRule = str_replace('{py}',GetPinyin($title,1).'_'.$aid,$articleRule); + $articleRule = str_replace($arr_rpsource, $arr_rpvalues, $articleRule); + if (preg_match("/\{p/", $articleRule)) { + $articleRule = str_replace('{pinyin}', GetPinyin($title) . '_' . $aid, $articleRule); + $articleRule = str_replace('{py}', GetPinyin($title, 1) . '_' . $aid, $articleRule); } - $articleUrl = '/'.preg_replace("/^\//", '', $articleRule); - if(preg_match("/index\.html/", $articleUrl) && $cfg_arc_dirname=='Y') - { + $articleUrl = '/' . preg_replace("/^\//", '', $articleRule); + if (preg_match("/index\.html/", $articleUrl) && $cfg_arc_dirname == 'Y') { $articleUrl = str_replace('index.html', '', $articleUrl); } return $articleUrl; @@ -204,7 +176,6 @@ function GetFileName($aid,$typeid,$timetag,$title,$ismake=0,$rank=0,$namerule='' } } - /** * 获得指定类目的URL链接 * 对于使用封面文件和单独页面的情况,强制使用默认页名称 @@ -220,53 +191,47 @@ function GetFileName($aid,$typeid,$timetag,$title,$ismake=0,$rank=0,$namerule='' * @param string $sitepath 站点目录 * @return string */ -if ( ! function_exists('GetTypeUrl')) -{ - function GetTypeUrl($typeid,$typedir,$isdefault,$defaultname,$ispart,$namerule2,$moresite=0,$siteurl='',$sitepath='') +if (!function_exists('GetTypeUrl')) { + function GetTypeUrl($typeid, $typedir, $isdefault, $defaultname, $ispart, $namerule2, $moresite = 0, $siteurl = '', $sitepath = '') { global $cfg_typedir_df; $typedir = MfTypedir($typedir); $sitepath = MfTypedir($sitepath); - if($isdefault==-1) - { + if ($isdefault == -1) { //动态 - $reurl = $GLOBALS['cfg_phpurl']."/list.php?tid=".$typeid; - } - else if($ispart==2) - { + $reurl = $GLOBALS['cfg_phpurl'] . "/list.php?tid=" . $typeid; + } else if ($ispart == 2) { //跳转网址 $reurl = $typedir; return $reurl; - } - else - { - if($isdefault==0 && $ispart==0) - { - $reurl = str_replace("{page}","1",$namerule2); - $reurl = str_replace("{tid}",$typeid,$reurl); - $reurl = str_replace("{typedir}",$typedir,$reurl); - } - else - { - if($cfg_typedir_df=='N' || $isdefault==0) $reurl = $typedir.'/'.$defaultname; - else $reurl = $typedir.'/'; + } else { + if ($isdefault == 0 && $ispart == 0) { + $reurl = str_replace("{page}", "1", $namerule2); + $reurl = str_replace("{tid}", $typeid, $reurl); + $reurl = str_replace("{typedir}", $typedir, $reurl); + } else { + if ($cfg_typedir_df == 'N' || $isdefault == 0) { + $reurl = $typedir . '/' . $defaultname; + } else { + $reurl = $typedir . '/'; + } + } } - if( !preg_match("/^http:\/\//",$reurl) ) { + if (!preg_match("/^http:\/\//", $reurl)) { $reurl = preg_replace("/\/{1,}/i", '/', $reurl); } - - if($GLOBALS['cfg_multi_site']=='Y') - { - if($siteurl=='') { + + if ($GLOBALS['cfg_multi_site'] == 'Y') { + if ($siteurl == '') { $siteurl = $GLOBALS['cfg_basehost']; } - if($moresite==1 ) { - $reurl = preg_replace("#^".$sitepath."#", '', $reurl); + if ($moresite == 1) { + $reurl = preg_replace("#^" . $sitepath . "#", '', $reurl); } - if( !preg_match("/^http:\/\//", $reurl) ) { - $reurl = $siteurl.$reurl; + if (!preg_match("/^http:\/\//", $reurl)) { + $reurl = $siteurl . $reurl; } } return $reurl; @@ -280,11 +245,10 @@ function GetTypeUrl($typeid,$typedir,$isdefault,$defaultname,$ispart,$namerule2, * @param string $v2 第二个变量 * @return string */ -if ( ! function_exists('MagicVar')) -{ - function MagicVar($v1,$v2) +if (!function_exists('MagicVar')) { + function MagicVar($v1, $v2) { - return $GLOBALS['autoindex']%2==0 ? $v1 : $v2; + return $GLOBALS['autoindex'] % 2 == 0 ? $v1 : $v2; } } @@ -294,17 +258,14 @@ function MagicVar($v1,$v2) * @param int $tid 栏目ID * @return string */ -if ( ! function_exists('GetTopids')) -{ +if (!function_exists('GetTopids')) { function GetTopids($tid) { $arr = GetParentIds($tid); - return join(',',$arr); + return join(',', $arr); } } - - /** * 获取上级ID列表 * @@ -312,28 +273,22 @@ function GetTopids($tid) * @param string $tid 栏目ID * @return string */ -if ( ! function_exists('GetParentIds')) -{ +if (!function_exists('GetParentIds')) { function GetParentIds($tid) { global $cfg_Cs; $GLOBALS['pTypeArrays'][] = $tid; - if(!is_array($cfg_Cs)) - { - require_once(DEDEDATA."/cache/inc_catalog_base.inc"); + if (!is_array($cfg_Cs)) { + require_once DEDEDATA . "/cache/inc_catalog_base.inc"; } - if(!isset($cfg_Cs[$tid]) || $cfg_Cs[$tid][0]==0) - { + if (!isset($cfg_Cs[$tid]) || $cfg_Cs[$tid][0] == 0) { return $GLOBALS['pTypeArrays']; - } - else - { + } else { return GetParentIds($cfg_Cs[$tid][0]); } } } - /** * 检测栏目是否是另一个栏目的父目录 * @@ -342,8 +297,7 @@ function GetParentIds($tid) * @param string $pid 下级目录id * @return bool */ -if ( ! function_exists('IsParent')) -{ +if (!function_exists('IsParent')) { function IsParent($sid, $pid) { $pTypeArrays = GetParentIds($sid); @@ -351,34 +305,27 @@ function IsParent($sid, $pid) } } - /** * 获取一个类目的顶级类目id * * @param string $tid 栏目ID * @return string */ -if ( ! function_exists('GetTopid')) -{ +if (!function_exists('GetTopid')) { function GetTopid($tid) { global $cfg_Cs; - if(!is_array($cfg_Cs)) - { - require_once(DEDEDATA."/cache/inc_catalog_base.inc"); + if (!is_array($cfg_Cs)) { + require_once DEDEDATA . "/cache/inc_catalog_base.inc"; } - if(!isset($cfg_Cs[$tid][0]) || $cfg_Cs[$tid][0]==0) - { + if (!isset($cfg_Cs[$tid][0]) || $cfg_Cs[$tid][0] == 0) { return $tid; - } - else - { + } else { return GetTopid($cfg_Cs[$tid][0]); } } } - /** * 获得某id的所有下级id * @@ -387,34 +334,29 @@ function GetTopid($tid) * @param string $addthis 是否包含本身 * @return string */ -function GetSonIds($id,$channel=0,$addthis=true) +function GetSonIds($id, $channel = 0, $addthis = true) { global $cfg_Cs; $GLOBALS['idArray'] = array(); - if( !is_array($cfg_Cs) ) - { - require_once(DEDEDATA."/cache/inc_catalog_base.inc"); + if (!is_array($cfg_Cs)) { + require_once DEDEDATA . "/cache/inc_catalog_base.inc"; } - GetSonIdsLogic($id,$cfg_Cs,$channel,$addthis); - $rquery = join(',',$GLOBALS['idArray']); - $rquery = preg_replace("/,$/", '', $rquery); + GetSonIdsLogic($id, $cfg_Cs, $channel, $addthis); + $rquery = join(',', $GLOBALS['idArray']); + $rquery = preg_replace("/,$/", '', $rquery); return $rquery; } //递归逻辑 -function GetSonIdsLogic($id,$sArr,$channel=0,$addthis=false) +function GetSonIdsLogic($id, $sArr, $channel = 0, $addthis = false) { - if($id!=0 && $addthis) - { + if ($id != 0 && $addthis) { $GLOBALS['idArray'][$id] = $id; } - if(is_array($sArr)) - { - foreach($sArr as $k=>$v) - { - if( $v[0]==$id && ($channel==0 || $v[1]==$channel )) - { - GetSonIdsLogic($k,$sArr,$channel,true); + if (is_array($sArr)) { + foreach ($sArr as $k => $v) { + if ($v[0] == $id && ($channel == 0 || $v[1] == $channel)) { + GetSonIdsLogic($k, $sArr, $channel, true); } } } @@ -428,8 +370,11 @@ function GetSonIdsLogic($id,$sArr,$channel=0,$addthis=false) */ function MfTypedir($typedir) { - if(preg_match("/^http:|^ftp:/i", $typedir)) return $typedir; - $typedir = str_replace("{cmspath}",$GLOBALS['cfg_cmspath'],$typedir); + if (preg_match("/^http:|^ftp:/i", $typedir)) { + return $typedir; + } + + $typedir = str_replace("{cmspath}", $GLOBALS['cfg_cmspath'], $typedir); $typedir = preg_replace("/\/{1,}/", "/", $typedir); return $typedir; } @@ -455,7 +400,7 @@ function MfTemplet($tmpdir) */ function FormatScript($atme) { - return $atme==' ' ? '' : $atme; + return $atme == ' ' ? '' : $atme; } /** @@ -468,11 +413,9 @@ function FormatScript($atme) function FillAttsDefault(&$atts, $attlist) { $attlists = explode(',', $attlist); - for($i=0; isset($attlists[$i]); $i++) - { + for ($i = 0;isset($attlists[$i]); $i++) { list($k, $v) = explode('|', $attlists[$i]); - if(!isset($atts[$k])) - { + if (!isset($atts[$k])) { $atts[$k] = $v; } } @@ -486,79 +429,67 @@ function FillAttsDefault(&$atts, $attlist) * @param object $parfield * @return string */ -function MakeOneTag(&$dtp, &$refObj, $parfield='Y') +function MakeOneTag(&$dtp, &$refObj, $parfield = 'Y') { global $cfg_disable_tags; - $cfg_disable_tags = isset($cfg_disable_tags)? $cfg_disable_tags : 'php'; + $cfg_disable_tags = isset($cfg_disable_tags) ? $cfg_disable_tags : 'php'; $disable_tags = explode(',', $cfg_disable_tags); $alltags = array(); $dtp->setRefObj($refObj); //读取自由调用tag列表 - $dh = dir(DEDEINC.'/taglib'); - while($filename = $dh->read()) - { - if(preg_match("/\.lib\./", $filename)) - { - $alltags[] = str_replace('.lib.php','',$filename); + $dh = dir(DEDEINC . '/taglib'); + while ($filename = $dh->read()) { + if (preg_match("/\.lib\./", $filename)) { + $alltags[] = str_replace('.lib.php', '', $filename); } } $dh->Close(); //遍历tag元素 - if(!is_array($dtp->CTags)) - { + if (!is_array($dtp->CTags)) { return ''; } - foreach($dtp->CTags as $tagid=>$ctag) - { + foreach ($dtp->CTags as $tagid => $ctag) { $tagname = $ctag->GetName(); - if($tagname=='field' && $parfield=='Y') - { + if ($tagname == 'field' && $parfield == 'Y') { $vname = $ctag->GetAtt('name'); - if( $vname=='array' && isset($refObj->Fields) ) - { - $dtp->Assign($tagid,$refObj->Fields); - } - else if(isset($refObj->Fields[$vname])) - { - $dtp->Assign($tagid,$refObj->Fields[$vname]); - } - else if($ctag->GetAtt('noteid') != '') - { - if( isset($refObj->Fields[$vname.'_'.$ctag->GetAtt('noteid')]) ) - { - $dtp->Assign($tagid, $refObj->Fields[$vname.'_'.$ctag->GetAtt('noteid')]); + if ($vname == 'array' && isset($refObj->Fields)) { + $dtp->Assign($tagid, $refObj->Fields); + } else if (isset($refObj->Fields[$vname])) { + $dtp->Assign($tagid, $refObj->Fields[$vname]); + } else if ($ctag->GetAtt('noteid') != '') { + if (isset($refObj->Fields[$vname . '_' . $ctag->GetAtt('noteid')])) { + $dtp->Assign($tagid, $refObj->Fields[$vname . '_' . $ctag->GetAtt('noteid')]); } } continue; } //由于考虑兼容性,原来文章调用使用的标记别名统一保留,这些标记实际调用的解析文件为inc_arclist.php - if(preg_match("/^(artlist|likeart|hotart|imglist|imginfolist|coolart|specart|autolist)$/", $tagname)) - { - $tagname='arclist'; + if (preg_match("/^(artlist|likeart|hotart|imglist|imginfolist|coolart|specart|autolist)$/", $tagname)) { + $tagname = 'arclist'; } - if($tagname=='friendlink') - { - $tagname='flink'; + if ($tagname == 'friendlink') { + $tagname = 'flink'; } - if(in_array($tagname,$alltags)) - { - if(in_array($tagname, $disable_tags)) - { - if(DEBUG_LEVEL) echo 'DedeCMS Error:Tag disabled:"'.$tagname.'" more...!'; + if (in_array($tagname, $alltags)) { + if (in_array($tagname, $disable_tags)) { + if (DEBUG_LEVEL) { + echo 'DedeCMS Error:Tag disabled:"' . $tagname . '" more...!'; + } + continue; } - if (DEBUG_LEVEL==TRUE) { + if (DEBUG_LEVEL == true) { $ttt1 = ExecTime(); } - $filename = DEDEINC.'/taglib/'.$tagname.'.lib.php'; - include_once($filename); - $funcname = 'lib_'.$tagname; - $dtp->Assign($tagid,$funcname($ctag,$refObj)); - if (DEBUG_LEVEL==TRUE) { + $filename = DEDEINC . '/taglib/' . $tagname . '.lib.php'; + include_once $filename; + $funcname = 'lib_' . $tagname; + $dtp->Assign($tagid, $funcname($ctag, $refObj)); + if (DEBUG_LEVEL == true) { $queryTime = ExecTime() - $ttt1; - echo '标签:'.$tagname.'载入花费时间:'.$queryTime."
\r\n"; + echo '标签:' . $tagname . '载入花费时间:' . $queryTime . "
\r\n"; } } } @@ -572,8 +503,8 @@ function MakeOneTag(&$dtp, &$refObj, $parfield='Y') */ function GetOneTypeUrlA($typeinfos) { - return GetTypeUrl($typeinfos['id'],MfTypedir($typeinfos['typedir']),$typeinfos['isdefault'],$typeinfos['defaultname'], - $typeinfos['ispart'],$typeinfos['namerule2'],$typeinfos['moresite'],$typeinfos['siteurl'],$typeinfos['sitepath']); + return GetTypeUrl($typeinfos['id'], MfTypedir($typeinfos['typedir']), $typeinfos['isdefault'], $typeinfos['defaultname'], + $typeinfos['ispart'], $typeinfos['namerule2'], $typeinfos['moresite'], $typeinfos['siteurl'], $typeinfos['sitepath']); } /** @@ -586,23 +517,19 @@ function GetOneTypeUrlA($typeinfos) * @param string $curfile 当前文件 * @return string */ -function SetSysEnv($typeid=0,$typename='',$aid=0,$title='',$curfile='') +function SetSysEnv($typeid = 0, $typename = '', $aid = 0, $title = '', $curfile = '') { global $_sys_globals; - if(empty($_sys_globals['curfile'])) - { + if (empty($_sys_globals['curfile'])) { $_sys_globals['curfile'] = $curfile; } - if(empty($_sys_globals['typeid'])) - { + if (empty($_sys_globals['typeid'])) { $_sys_globals['typeid'] = $typeid; } - if(empty($_sys_globals['typename'])) - { + if (empty($_sys_globals['typename'])) { $_sys_globals['typename'] = $typename; } - if(empty($_sys_globals['aid'])) - { + if (empty($_sys_globals['aid'])) { $_sys_globals['aid'] = $aid; } } @@ -615,11 +542,11 @@ function SetSysEnv($typeid=0,$typename='',$aid=0,$title='',$curfile='') * @param string $gdir * @return string */ -function GetBookUrl($bid,$title,$gdir=0) +function GetBookUrl($bid, $title, $gdir = 0) { global $cfg_cmspath; - $bookurl = $gdir==1 ? - "{$cfg_cmspath}/book/".DedeID2Dir($bid) : "{$cfg_cmspath}/book/".DedeID2Dir($bid).'/'.GetPinyin($title).'-'.$bid.'.html'; + $bookurl = $gdir == 1 ? + "{$cfg_cmspath}/book/" . DedeID2Dir($bid) : "{$cfg_cmspath}/book/" . DedeID2Dir($bid) . '/' . GetPinyin($title) . '-' . $bid . '.html'; return $bookurl; } @@ -645,25 +572,22 @@ function DedeID2Dir($aid) * @param string $nodefault 没有默认页面 * @return string */ -function GetFreeListUrl($lid,$namerule,$listdir,$defaultpage,$nodefault){ - $listdir = str_replace('{cmspath}',$GLOBALS['cfg_cmspath'],$listdir); - if($nodefault==1) - { - $okfile = str_replace('{page}','1',$namerule); - $okfile = str_replace('{listid}',$lid,$okfile); - $okfile = str_replace('{listdir}',$listdir,$okfile); - } - else - { - $okfile = $GLOBALS['cfg_phpurl']."/freelist.php?lid=$lid"; +function GetFreeListUrl($lid, $namerule, $listdir, $defaultpage, $nodefault) +{ + $listdir = str_replace('{cmspath}', $GLOBALS['cfg_cmspath'], $listdir); + if ($nodefault == 1) { + $okfile = str_replace('{page}', '1', $namerule); + $okfile = str_replace('{listid}', $lid, $okfile); + $okfile = str_replace('{listdir}', $listdir, $okfile); + } else { + $okfile = $GLOBALS['cfg_phpurl'] . "/freelist.php?lid=$lid"; return $okfile; } - $okfile = str_replace("\\","/",$okfile); - $okfile = str_replace("//","/",$okfile); - $trueFile = $GLOBALS['cfg_basedir'].$okfile; - if(!@file_exists($trueFile)) - { - $okfile = $GLOBALS['cfg_phpurl']."/freelist.php?lid=$lid"; + $okfile = str_replace("\\", "/", $okfile); + $okfile = str_replace("//", "/", $okfile); + $trueFile = $GLOBALS['cfg_basedir'] . $okfile; + if (!@file_exists($trueFile)) { + $okfile = $GLOBALS['cfg_phpurl'] . "/freelist.php?lid=$lid"; } return $okfile; } @@ -678,37 +602,32 @@ function GetFreeListUrl($lid,$namerule,$listdir,$defaultpage,$nodefault){ * @param string $orderby 排列顺序 * @return string */ -function GetHotKeywords(&$dsql,$num=8,$nday=365,$klen=16,$orderby='count') +function GetHotKeywords(&$dsql, $num = 8, $nday = 365, $klen = 16, $orderby = 'count') { - global $cfg_phpurl,$cfg_cmspath; + global $cfg_phpurl, $cfg_cmspath; $nowtime = time(); $num = @intval($num); $nday = @intval($nday); $klen = @intval($klen); - if(empty($nday)) - { + if (empty($nday)) { $nday = 365; } - if(empty($num)) - { + if (empty($num)) { $num = 6; } - if(empty($klen)) - { + if (empty($klen)) { $klen = 16; } - $klen = $klen+1; + $klen = $klen + 1; $mintime = $nowtime - ($nday * 24 * 3600); - if(empty($orderby)) - { + if (empty($orderby)) { $orderby = 'count'; } $dsql->SetQuery("SELECT keyword FROM #@__search_keywords WHERE lasttime>$mintime AND length(keyword)<$klen ORDER BY $orderby DESC LIMIT 0,$num"); $dsql->Execute('hw'); $hotword = ""; - while($row=$dsql->GetArray('hw')) - { - $hotword .= " ".$row['keyword']." "; + while ($row = $dsql->GetArray('hw')) { + $hotword .= " " . $row['keyword'] . " "; } return $hotword; } @@ -721,7 +640,7 @@ function GetHotKeywords(&$dsql,$num=8,$nday=365,$klen=16,$orderby='count') */ function Gmapurl($gurl) { - return preg_replace("/http:\/\//i", $gurl) ? $gurl : $GLOBALS['cfg_basehost'].$gurl; + return preg_replace("/http:\/\//i", $gurl) ? $gurl : $GLOBALS['cfg_basehost'] . $gurl; } /** @@ -732,15 +651,15 @@ function Gmapurl($gurl) */ function Quote_replace($quote) { - $quote = str_replace('{quote}','
',$quote); - $quote = str_replace('{title}','
',$quote); - $quote = str_replace('{/title}','
',$quote); - $quote = str_replace('<br/>','
',$quote); + $quote = str_replace('{quote}', '
', $quote); + $quote = str_replace('{title}', '
', $quote); + $quote = str_replace('{/title}', '
', $quote); + $quote = str_replace('<br/>', '
', $quote); $quote = str_replace('<', '<', $quote); $quote = str_replace('>', '>', $quote); - $quote = str_replace('{content}','
',$quote); - $quote = str_replace('{/content}','
',$quote); - $quote = str_replace('{/quote}','
',$quote); + $quote = str_replace('{content}', '
', $quote); + $quote = str_replace('{/content}', '
', $quote); + $quote = str_replace('{/quote}', '
', $quote); return $quote; } @@ -753,10 +672,9 @@ function Quote_replace($quote) function GetCacheBlock($cacheid) { global $cfg_puccache_time; - $cachefile = DEDEDATA.'/cache/'.$cacheid.'.inc'; - if(!file_exists($cachefile) || filesize($cachefile)==0 || - $cfg_puccache_time==0 || time() - filemtime($cachefile) > $cfg_puccache_time) - { + $cachefile = DEDEDATA . '/cache/' . $cacheid . '.inc'; + if (!file_exists($cachefile) || filesize($cachefile) == 0 || + $cfg_puccache_time == 0 || time() - filemtime($cachefile) > $cfg_puccache_time) { return ''; } $fp = fopen($cachefile, 'r'); @@ -774,7 +692,7 @@ function GetCacheBlock($cacheid) */ function WriteCacheBlock($cacheid, $str) { - $cachefile = DEDEDATA.'/cache/'.$cacheid.'.inc'; + $cachefile = DEDEDATA . '/cache/' . $cacheid . '.inc'; $fp = fopen($cachefile, 'w'); $str = fwrite($fp, $str); fclose($fp); diff --git a/include/helpers/charset.helper.php b/include/helpers/charset.helper.php index 1ed91c9e..ba4ccd4c 100755 --- a/include/helpers/charset.helper.php +++ b/include/helpers/charset.helper.php @@ -1,4 +1,4 @@ - 0x80) - { + while ($gbstr != '') { + if (ord(substr($gbstr, 0, 1)) > 0x80) { $thisW = substr($gbstr, 0, 2); $gbstr = substr($gbstr, 2, strlen($gbstr)); $utf8 = ""; @$utf8 = u2utf8(hexdec($CODETABLE[hexdec(bin2hex($thisW)) - 0x8080])); - if($utf8!="") - { - for ($i = 0;$i < strlen($utf8);$i += 3) - $ret .= chr(substr($utf8, $i, 3)); + if ($utf8 != "") { + for ($i = 0; $i < strlen($utf8); $i += 3) { + $ret .= chr(substr($utf8, $i, 3)); + } + } - } - else - { + } else { $ret .= substr($gbstr, 0, 1); $gbstr = substr($gbstr, 1, strlen($gbstr)); } @@ -141,31 +120,22 @@ function gb2utf8($gbstr) * @param string $c Unicode的字符串内容 * @return string */ -if ( ! function_exists('u2utf8')) -{ +if (!function_exists('u2utf8')) { function u2utf8($c) { - for ($i = 0;$i < count($c);$i++) - { + for ($i = 0; $i < count($c); $i++) { $str = ""; } - if ($c < 0x80) - { + if ($c < 0x80) { $str .= $c; - } - else if ($c < 0x800) - { + } else if ($c < 0x800) { $str .= (0xC0 | $c >> 6); $str .= (0x80 | $c & 0x3F); - } - else if ($c < 0x10000) - { + } else if ($c < 0x10000) { $str .= (0xE0 | $c >> 12); $str .= (0x80 | $c >> 6 & 0x3F); $str .= (0x80 | $c & 0x3F); - } - else if ($c < 0x200000) - { + } else if ($c < 0x200000) { $str .= (0xF0 | $c >> 18); $str .= (0x80 | $c >> 12 & 0x3F); $str .= (0x80 | $c >> 6 & 0x3F); @@ -182,12 +152,10 @@ function u2utf8($c) * @param string $c UTF-8的字符串信息 * @return string */ -if ( ! function_exists('utf82u')) -{ +if (!function_exists('utf82u')) { function utf82u($c) { - switch(strlen($c)) - { + switch (strlen($c)) { case 1: return ord($c); case 2: @@ -216,40 +184,32 @@ function utf82u($c) * @param string $Text 字符串内容 * @return string */ -if ( ! function_exists('big52gb')) -{ +if (!function_exists('big52gb')) { function big52gb($Text) { - if(function_exists('iconv')) - { - return iconv('big5','gbk//ignore',$Text); + if (function_exists('iconv')) { + return iconv('big5', 'gbk//ignore', $Text); } global $BIG5_DATA; - if(empty($BIG5_DATA)) - { - $filename = DEDEINC."/data/big5-gb.dat"; + if (empty($BIG5_DATA)) { + $filename = DEDEINC . "/data/big5-gb.dat"; $fp = fopen($filename, "rb"); - $BIG5_DATA = fread($fp,filesize($filename)); + $BIG5_DATA = fread($fp, filesize($filename)); fclose($fp); } - $max = strlen($Text)-1; - for($i=0;$i<$max;$i++) - { + $max = strlen($Text) - 1; + for ($i = 0; $i < $max; $i++) { $h = ord($Text[$i]); - if($h>=0x80) - { - $l = ord($Text[$i+1]); - if($h==161 && $l==64) - { + if ($h >= 0x80) { + $l = ord($Text[$i + 1]); + if ($h == 161 && $l == 64) { $gbstr = " "; - } - else - { - $p = ($h-160)*510+($l-1)*2; - $gbstr = $BIG5_DATA[$p].$BIG5_DATA[$p+1]; + } else { + $p = ($h - 160) * 510 + ($l - 1) * 2; + $gbstr = $BIG5_DATA[$p] . $BIG5_DATA[$p + 1]; } $Text[$i] = $gbstr[0]; - $Text[$i+1] = $gbstr[1]; + $Text[$i + 1] = $gbstr[1]; $i++; } } @@ -264,40 +224,32 @@ function big52gb($Text) * @param string $Text 字符串内容 * @return string */ -if ( ! function_exists('gb2big5')) -{ +if (!function_exists('gb2big5')) { function gb2big5($Text) { - if(function_exists('iconv')) - { - return iconv('gbk','big5//ignore',$Text); + if (function_exists('iconv')) { + return iconv('gbk', 'big5//ignore', $Text); } global $GB_DATA; - if(empty($GB_DATA)) - { - $filename = DEDEINC."/data/gb-big5.dat"; + if (empty($GB_DATA)) { + $filename = DEDEINC . "/data/gb-big5.dat"; $fp = fopen($filename, "rb"); - $gb = fread($fp,filesize($filename)); + $gb = fread($fp, filesize($filename)); fclose($fp); } - $max = strlen($Text)-1; - for($i=0;$i<$max;$i++) - { + $max = strlen($Text) - 1; + for ($i = 0; $i < $max; $i++) { $h = ord($Text[$i]); - if($h>=0x80) - { - $l = ord($Text[$i+1]); - if($h==161 && $l==64) - { + if ($h >= 0x80) { + $l = ord($Text[$i + 1]); + if ($h == 161 && $l == 64) { $big = " "; - } - else - { - $p = ($h-160)*510+($l-1)*2; - $big = $GB_DATA[$p].$GB_DATA[$p+1]; + } else { + $p = ($h - 160) * 510 + ($l - 1) * 2; + $big = $GB_DATA[$p] . $GB_DATA[$p + 1]; } $Text[$i] = $big[0]; - $Text[$i+1] = $big[1]; + $Text[$i + 1] = $big[1]; $i++; } } @@ -312,49 +264,36 @@ function gb2big5($Text) * @param string $str 转换的内容 * @return string */ -if ( ! function_exists('UnicodeUrl2Gbk')) -{ +if (!function_exists('UnicodeUrl2Gbk')) { function UnicodeUrl2Gbk($str) { //载入对照词典 - if(!isset($GLOBALS['GbkUniDic'])) - { - $fp = fopen(DEDEINC.'/data/gbk-unicode.dat','rb'); - while(!feof($fp)) - { - $GLOBALS['GbkUniDic'][bin2hex(fread($fp,2))] = fread($fp,2); + if (!isset($GLOBALS['GbkUniDic'])) { + $fp = fopen(DEDEINC . '/data/gbk-unicode.dat', 'rb'); + while (!feof($fp)) { + $GLOBALS['GbkUniDic'][bin2hex(fread($fp, 2))] = fread($fp, 2); } fclose($fp); } //处理字符串 - $str = str_replace('$#$','+',$str); + $str = str_replace('$#$', '+', $str); $glen = strlen($str); $okstr = ""; - for($i=0; $i < $glen; $i++) - { - if($glen-$i > 4) - { - if($str[$i]=='%' && $str[$i+1]=='u') - { - $uni = strtolower(substr($str,$i+2,4)); - $i = $i+5; - if(isset($GLOBALS['GbkUniDic'][$uni])) - { + for ($i = 0; $i < $glen; $i++) { + if ($glen - $i > 4) { + if ($str[$i] == '%' && $str[$i + 1] == 'u') { + $uni = strtolower(substr($str, $i + 2, 4)); + $i = $i + 5; + if (isset($GLOBALS['GbkUniDic'][$uni])) { $okstr .= $GLOBALS['GbkUniDic'][$uni]; + } else { + $okstr .= "&#" . hexdec('0x' . $uni) . ";"; } - else - { - $okstr .= "&#".hexdec('0x'.$uni).";"; - } - } - else - { + } else { $okstr .= $str[$i]; } - } - else - { + } else { $okstr .= $str[$i]; } } @@ -369,40 +308,34 @@ function UnicodeUrl2Gbk($str) * @param string $str 转换的内容 * @return string */ -if ( ! function_exists('AutoCharset')) -{ - function AutoCharset($fContents, $from='gbk', $to='utf-8') +if (!function_exists('AutoCharset')) { + function AutoCharset($fContents, $from = 'gbk', $to = 'utf-8') { - $from = strtoupper($from)=='UTF8'? 'utf-8' : $from; - $to = strtoupper($to)=='UTF8'? 'utf-8' : $to; - if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){ + $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from; + $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to; + if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) { //如果编码相同或者非字符串标量则不转换 return $fContents; } - if(is_string($fContents) ) - { - if(function_exists('mb_convert_encoding')) - { - return mb_convert_encoding ($fContents, $to, $from); - } elseif (function_exists('iconv')) - { + if (is_string($fContents)) { + if (function_exists('mb_convert_encoding')) { + return mb_convert_encoding($fContents, $to, $from); + } elseif (function_exists('iconv')) { return iconv($from, $to, $fContents); } else { return $fContents; } - } - elseif(is_array($fContents)) - { - foreach ( $fContents as $key => $val ) - { - $_key = AutoCharset($key,$from,$to); - $fContents[$_key] = AutoCharset($val,$from,$to); - if($key != $_key ) + } elseif (is_array($fContents)) { + foreach ($fContents as $key => $val) { + $_key = AutoCharset($key, $from, $to); + $fContents[$_key] = AutoCharset($val, $from, $to); + if ($key != $_key) { unset($fContents[$key]); + } + } return $fContents; - } - else{ + } else { return $fContents; } } diff --git a/include/helpers/cookie.helper.php b/include/helpers/cookie.helper.php index 1bf03d70..8bdca856 100755 --- a/include/helpers/cookie.helper.php +++ b/include/helpers/cookie.helper.php @@ -1,4 +1,4 @@ -".$label.htmlspecialchars($output,ENT_QUOTES).""; + $output = "
" . $label . htmlspecialchars($output, ENT_QUOTES) . "
"; } else { $output = $label . " : " . print_r($var, true); } - }else { + } else { ob_start(); var_dump($var); $output = ob_get_clean(); - if(!extension_loaded('xdebug')) { + if (!extension_loaded('xdebug')) { $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output); - $output = '
'. $label. htmlspecialchars($output, ENT_QUOTES). '
'; + $output = '
' . $label . htmlspecialchars($output, ENT_QUOTES) . '
'; } } if ($echo) { - echo($output); + echo ($output); return null; - }else + } else { return $output; + } + } } @@ -56,13 +57,12 @@ function Dump($var, $echo=true, $label=null, $strict=true) * * @return int */ -if ( ! function_exists('ExecTime')) -{ +if (!function_exists('ExecTime')) { function ExecTime() { $time = explode(" ", microtime()); - $usec = (double)$time[0]; - $sec = (double)$time[1]; + $usec = (double) $time[0]; + $sec = (double) $time[1]; return $sec + $usec; } } diff --git a/include/helpers/downmix.helper.php b/include/helpers/downmix.helper.php index 197f8a9a..430ad77a 100755 --- a/include/helpers/downmix.helper.php +++ b/include/helpers/downmix.helper.php @@ -1,4 +1,4 @@ - $rndstyleValue \r\n"; @@ -51,26 +50,22 @@ function RndString(&$body) $rndem[4] = 'p'; //读取字符串数据 - $fp = fopen(DEDEDATA.'/downmix.data.php','r'); + $fp = fopen(DEDEDATA . '/downmix.data.php', 'r'); $start = 0; $totalitem = 0; - while(!feof($fp)) - { - $v = trim(fgets($fp,128)); - if($start==1) - { - if(preg_match("/#end#/i", $v)) - { + while (!feof($fp)) { + $v = trim(fgets($fp, 128)); + if ($start == 1) { + if (preg_match("/#end#/i", $v)) { break; } - if($v!='') - { - $totalitem++; $rndstring[$totalitem] = preg_replace("/#,/", "", $v); + if ($v != '') { + $totalitem++; + $rndstring[$totalitem] = preg_replace("/#,/", "", $v); } } - if(preg_match("/#start#/i", $v)) - { + if (preg_match("/#start#/i", $v)) { $start = 1; } } @@ -79,38 +74,28 @@ function RndString(&$body) //处理要防采集的字段 $bodylen = strlen($body) - 1; $prepos = 0; - for($i=0;$i<=$bodylen;$i++) - { - if($i+2 >= $bodylen || $i<50) - { + for ($i = 0; $i <= $bodylen; $i++) { + if ($i + 2 >= $bodylen || $i < 50) { $reString .= $body[$i]; - } - else - { - $ntag = @strtolower($body[$i].$body[$i+1].$body[$i+2]); - if($ntag=='$maxpos) ) - { - $dd = mt_rand(1,4); + } else { + $ntag = @strtolower($body[$i] . $body[$i + 1] . $body[$i + 2]); + if ($ntag == ' $maxpos)) { + $dd = mt_rand(1, 4); $emname = $rndem[$dd]; - $dd = mt_rand(1,$totalitem); + $dd = mt_rand(1, $totalitem); $rnstr = $rndstring[$dd]; - if($emname!='font') - { + if ($emname != 'font') { $rnstr = " <$emname class='$rndstyleName'>$rnstr "; - } - else - { + } else { $rnstr = " $rnstr "; } - $reString .= $rnstr.$body[$i]; + $reString .= $rnstr . $body[$i]; $prepos = $i; - } - else - { + } else { $reString .= $body[$i]; } } } return $reString; - }//函数结束 + } //函数结束 } diff --git a/include/helpers/extend.helper.php b/include/helpers/extend.helper.php index 1099de21..8521c826 100755 --- a/include/helpers/extend.helper.php +++ b/include/helpers/extend.helper.php @@ -1,4 +1,4 @@ -')) - $res = $res.'<'.$strs[$i]; - else - $res = $res.'<'.$strs[$i]; - } - return strip_tags($res); - } -} +if (!function_exists('dede_strip_tags')) { + function dede_strip_tags($str) + { + $strs = explode('<', $str); + $res = $strs[0]; + for ($i = 1; $i < count($strs); $i++) { + if (!strpos($strs[$i], '>')) { + $res = $res . '<' . $strs[$i]; + } else { + $res = $res . '<' . $strs[$i]; + } + } + return strip_tags($res); + } +} diff --git a/include/helpers/file.helper.php b/include/helpers/file.helper.php index 8a9a5b6f..061f9670 100755 --- a/include/helpers/file.helper.php +++ b/include/helpers/file.helper.php @@ -1,4 +1,4 @@ -]*)>(.*)<\/style>/i", '', $str); - if($rptype==0) - { + if ($rptype == 0) { $str = dede_htmlspecialchars($str); - } - else if($rptype==1) - { + } else if ($rptype == 1) { $str = dede_htmlspecialchars($str); $str = str_replace(" ", ' ', $str); $str = preg_replace("/[\r\n\t ]{1,}/", ' ', $str); - } - else if($rptype==2) - { + } else if ($rptype == 2) { $str = dede_htmlspecialchars($str); $str = str_replace(" ", '', $str); $str = preg_replace("/[\r\n\t ]/", '', $str); - } - else - { + } else { $str = preg_replace("/[\r\n\t ]{1,}/", ' ', $str); $str = preg_replace('/script/i', 'script', $str); $str = preg_replace("/<[\/]{0,1}(link|meta|ifr|fra)[^>]*>/i", '', $str); @@ -54,55 +46,53 @@ function HtmlReplace($str,$rptype=0) } } - - /** * 修复浏览器XSS hack的函数 * * @param string $val 需要处理的内容 * @return string */ -if ( ! function_exists('RemoveXSS')) -{ - function RemoveXSS($val) { - $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); - $search = 'abcdefghijklmnopqrstuvwxyz'; - $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - $search .= '1234567890!@#$%^&*()'; - $search .= '~`";:?+/={}[]-_|\'\\'; - for ($i = 0; $i < strlen($search); $i++) { - $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ; - $val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; - } +if (!function_exists('RemoveXSS')) { + function RemoveXSS($val) + { + $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); + $search = 'abcdefghijklmnopqrstuvwxyz'; + $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + $search .= '1234567890!@#$%^&*()'; + $search .= '~`";:?+/={}[]-_|\'\\'; + for ($i = 0; $i < strlen($search); $i++) { + $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ; + $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ; + } - $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'); - $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'); - $ra = array_merge($ra1, $ra2); + $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'); + $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'); + $ra = array_merge($ra1, $ra2); - $found = true; - while ($found == true) { - $val_before = $val; - for ($i = 0; $i < sizeof($ra); $i++) { - $pattern = '/'; - for ($j = 0; $j < strlen($ra[$i]); $j++) { - if ($j > 0) { - $pattern .= '('; - $pattern .= '(&#[xX]0{0,8}([9ab]);)'; - $pattern .= '|'; - $pattern .= '|(�{0,8}([9|10|13]);)'; - $pattern .= ')*'; + $found = true; + while ($found == true) { + $val_before = $val; + for ($i = 0; $i < sizeof($ra); $i++) { + $pattern = '/'; + for ($j = 0; $j < strlen($ra[$i]); $j++) { + if ($j > 0) { + $pattern .= '('; + $pattern .= '(&#[xX]0{0,8}([9ab]);)'; + $pattern .= '|'; + $pattern .= '|(�{0,8}([9|10|13]);)'; + $pattern .= ')*'; + } + $pattern .= $ra[$i][$j]; } - $pattern .= $ra[$i][$j]; - } - $pattern .= '/i'; - $replacement = substr($ra[$i], 0, 2).''.substr($ra[$i], 2); - $val = preg_replace($pattern, $replacement, $val); - if ($val_before == $val) { - $found = false; - } - } - } - return $val; + $pattern .= '/i'; + $replacement = substr($ra[$i], 0, 2) . '' . substr($ra[$i], 2); + $val = preg_replace($pattern, $replacement, $val); + if ($val_before == $val) { + $found = false; + } + } + } + return $val; } } @@ -113,13 +103,12 @@ function RemoveXSS($val) { * @param string $msg 需要过滤的内容 * @return string */ -if ( ! function_exists('TrimMsg')) -{ +if (!function_exists('TrimMsg')) { function TrimMsg($msg) { $msg = trim(stripslashes($msg)); $msg = nl2br(dede_htmlspecialchars($msg)); - $msg = str_replace(" ","  ",$msg); + $msg = str_replace(" ", "  ", $msg); return addslashes($msg); } } @@ -130,48 +119,31 @@ function TrimMsg($msg) * @param string $keyword 关键词 * @return string */ -if ( ! function_exists('FilterSearch')) -{ +if (!function_exists('FilterSearch')) { function FilterSearch($keyword) { global $cfg_soft_lang; - if($cfg_soft_lang=='utf-8') - { + if ($cfg_soft_lang == 'utf-8') { $keyword = preg_replace("/[\"\r\n\t\$\\><']/", '', $keyword); - if($keyword != stripslashes($keyword)) - { + if ($keyword != stripslashes($keyword)) { return ''; - } - else - { + } else { return $keyword; } - } - else - { + } else { $restr = ''; - for($i=0;isset($keyword[$i]);$i++) - { - if(ord($keyword[$i]) > 0x80) - { - if(isset($keyword[$i+1]) && ord($keyword[$i+1]) > 0x40) - { - $restr .= $keyword[$i].$keyword[$i+1]; + for ($i = 0;isset($keyword[$i]); $i++) { + if (ord($keyword[$i]) > 0x80) { + if (isset($keyword[$i + 1]) && ord($keyword[$i + 1]) > 0x40) { + $restr .= $keyword[$i] . $keyword[$i + 1]; $i++; - } - else - { + } else { $restr .= ' '; } - } - else - { - if(preg_match("/[^0-9a-z@#\.]/",$keyword[$i])) - { + } else { + if (preg_match("/[^0-9a-z@#\.]/", $keyword[$i])) { $restr .= ' '; - } - else - { + } else { $restr .= $keyword[$i]; } } @@ -180,4 +152,3 @@ function FilterSearch($keyword) return $restr; } } - diff --git a/include/helpers/image.helper.php b/include/helpers/image.helper.php index d4cf8b3f..e861ef56 100755 --- a/include/helpers/image.helper.php +++ b/include/helpers/image.helper.php @@ -1,4 +1,4 @@ -$toW||$srcH>$toH) - { - if(function_exists("imagecreateTRUEcolor")) - { - @$ni = imagecreateTRUEcolor($ftoW,$ftoH); - if($ni) - { - imagecopyresampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH); - } - else - { - $ni=imagecreate($ftoW,$ftoH); - imagecopyresized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH); + if ($srcW > $toW || $srcH > $toH) { + if (function_exists("imagecreateTRUEcolor")) { + @$ni = imagecreateTRUEcolor($ftoW, $ftoH); + if ($ni) { + imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); + } else { + $ni = imagecreate($ftoW, $ftoH); + imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } + } else { + $ni = imagecreate($ftoW, $ftoH); + imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } - else - { - $ni=imagecreate($ftoW,$ftoH); - imagecopyresized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH); - } - switch ($srcInfo[2]) - { + switch ($srcInfo[2]) { case 1: - imagegif($ni,$toFile); + imagegif($ni, $toFile); break; case 2: - imagejpeg($ni,$toFile,85); + imagejpeg($ni, $toFile, 85); break; case 3: - imagepng($ni,$toFile); + imagepng($ni, $toFile); break; case 6: - imagebmp($ni,$toFile); + imagebmp($ni, $toFile); break; default: - return FALSE; + return false; } imagedestroy($ni); } imagedestroy($im); - return TRUE; + return true; } } - - /** * 获得GD的版本 @@ -115,34 +118,24 @@ function ImageResize($srcFile, $toW, $toH, $toFile="") * @access public * @return int */ -if ( ! function_exists('gdversion')) -{ +if (!function_exists('gdversion')) { function gdversion() { //没启用php.ini函数的情况下如果有GD默认视作2.0以上版本 - if(!function_exists('phpinfo')) - { - if(function_exists('imagecreate')) - { + if (!function_exists('phpinfo')) { + if (function_exists('imagecreate')) { return '2.0'; - } - else - { + } else { return 0; } - } - else - { + } else { ob_start(); phpinfo(8); $module_info = ob_get_contents(); ob_end_clean(); - if(preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i", $module_info,$matches)) - { + if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i", $module_info, $matches)) { $gdversion_h = $matches[1]; - } - else - { + } else { $gdversion_h = 0; } return $gdversion_h; @@ -150,7 +143,6 @@ function gdversion() } } - /** * 图片自动加水印函数 * @@ -159,56 +151,44 @@ function gdversion() * @param string $fromGo 位置 * @return string */ -if ( ! function_exists('WaterImg')) -{ - function WaterImg($srcFile, $fromGo='up') +if (!function_exists('WaterImg')) { + function WaterImg($srcFile, $fromGo = 'up') { - include(DEDEDATA.'/mark/inc_photowatermark_config.php'); - require_once(DEDEINC.'/image.class.php'); - if( isset($GLOBALS['needwatermark']) ) - { + include DEDEDATA . '/mark/inc_photowatermark_config.php'; + require_once DEDEINC . '/image.class.php'; + if (isset($GLOBALS['needwatermark'])) { $photo_markup = $photo_markdown = empty($GLOBALS['needwatermark']) ? '0' : '1'; } - if($photo_markup != '1' || ($fromGo=='collect' && $photo_markdown!='1') ) - { + if ($photo_markup != '1' || ($fromGo == 'collect' && $photo_markdown != '1')) { return; } $info = ''; - $srcInfo = @getimagesize($srcFile,$info); - $srcFile_w = $srcInfo[0]; - $srcFile_h = $srcInfo[1]; - - if($srcFile_w < $photo_wwidth || $srcFile_h < $photo_wheight) - { + $srcInfo = @getimagesize($srcFile, $info); + $srcFile_w = $srcInfo[0]; + $srcFile_h = $srcInfo[1]; + + if ($srcFile_w < $photo_wwidth || $srcFile_h < $photo_wheight) { return; } - if($fromGo=='up' && $photo_markup=='0') - { + if ($fromGo == 'up' && $photo_markup == '0') { return; } - if($fromGo=='down' && $photo_markdown=='0') - { + if ($fromGo == 'down' && $photo_markdown == '0') { return; } - $TRUEMarkimg = DEDEDATA.'/mark/'.$photo_markimg; - if(!file_exists($TRUEMarkimg) || empty($photo_markimg)) - { + $TRUEMarkimg = DEDEDATA . '/mark/' . $photo_markimg; + if (!file_exists($TRUEMarkimg) || empty($photo_markimg)) { $TRUEMarkimg = ""; } - if($photo_waterpos == 0) - { + if ($photo_waterpos == 0) { $photo_waterpos = rand(1, 9); } $cfg_watermarktext = array(); - if($photo_marktype == '2') - { - if(file_exists(DEDEDATA.'/mark/simhei.ttf')) - { - $cfg_watermarktext['fontpath'] = DEDEDATA.'/mark/simhei.ttf'; - } - else - { - return ; + if ($photo_marktype == '2') { + if (file_exists(DEDEDATA . '/mark/simhei.ttf')) { + $cfg_watermarktext['fontpath'] = DEDEDATA . '/mark/simhei.ttf'; + } else { + return; } } $cfg_watermarktext['text'] = $photo_watertext; @@ -219,7 +199,7 @@ function WaterImg($srcFile, $fromGo='up') $cfg_watermarktext['shadowy'] = '0'; $cfg_watermarktext['shadowcolor'] = '0,0,0'; $photo_marktrans = 85; - $img = new image($srcFile,0, $cfg_watermarktext, $photo_waterpos, $photo_diaphaneity, $photo_wheight, $photo_wwidth, $photo_marktype, $photo_marktrans,$TRUEMarkimg); + $img = new image($srcFile, 0, $cfg_watermarktext, $photo_waterpos, $photo_diaphaneity, $photo_wheight, $photo_wwidth, $photo_marktype, $photo_marktrans, $TRUEMarkimg); $img->watermark(0); } } @@ -235,30 +215,43 @@ function WaterImg($srcFile, $fromGo='up') * @param string $issave 是否保存 * @return bool */ -if ( ! function_exists('ImageResizeNew')) -{ - function ImageResizeNew($srcFile, $toW, $toH, $toFile='', $issave=TRUE) +if (!function_exists('ImageResizeNew')) { + function ImageResizeNew($srcFile, $toW, $toH, $toFile = '', $issave = true) { global $cfg_photo_type, $cfg_ddimg_bgcolor; - if($toFile=='') $toFile = $srcFile; + if ($toFile == '') { + $toFile = $srcFile; + } + $info = ''; - $srcInfo = GetImageSize($srcFile,$info); - switch ($srcInfo[2]) - { + $srcInfo = GetImageSize($srcFile, $info); + switch ($srcInfo[2]) { case 1: - if(!$cfg_photo_type['gif']) return FALSE; + if (!$cfg_photo_type['gif']) { + return false; + } + $img = imagecreatefromgif($srcFile); break; case 2: - if(!$cfg_photo_type['jpeg']) return FALSE; + if (!$cfg_photo_type['jpeg']) { + return false; + } + $img = imagecreatefromjpeg($srcFile); break; case 3: - if(!$cfg_photo_type['png']) return FALSE; + if (!$cfg_photo_type['png']) { + return false; + } + $img = imagecreatefrompng($srcFile); break; case 6: - if(!$cfg_photo_type['bmp']) return FALSE; + if (!$cfg_photo_type['bmp']) { + return false; + } + $img = imagecreatefromwbmp($srcFile); break; } @@ -267,7 +260,7 @@ function ImageResizeNew($srcFile, $toW, $toH, $toFile='', $issave=TRUE) $height = imageSY($img); if (!$width || !$height) { - return FALSE; + return false; } $target_width = $toW; @@ -292,30 +285,29 @@ function ImageResizeNew($srcFile, $toW, $toH, $toFile='', $issave=TRUE) } $new_img = ImageCreateTrueColor($target_width, $target_height); - - if($cfg_ddimg_bgcolor==0) $bgcolor = ImageColorAllocate($new_img, 0xff, 0xff, 0xff); - else $bgcolor = 0; - - if (!@imagefilledrectangle($new_img, 0, 0, $target_width-1, $target_height-1, $bgcolor)) - { - return FALSE; + + if ($cfg_ddimg_bgcolor == 0) { + $bgcolor = ImageColorAllocate($new_img, 0xff, 0xff, 0xff); + } else { + $bgcolor = 0; + } + + if (!@imagefilledrectangle($new_img, 0, 0, $target_width - 1, $target_height - 1, $bgcolor)) { + return false; } - if (!@imagecopyresampled($new_img, $img, ($target_width-$new_width)/2, ($target_height-$new_height)/2, 0, 0, $new_width, $new_height, $width, $height)) - { - return FALSE; + if (!@imagecopyresampled($new_img, $img, ($target_width - $new_width) / 2, ($target_height - $new_height) / 2, 0, 0, $new_width, $new_height, $width, $height)) { + return false; } - + //保存为目标文件 - if($issave) - { - switch ($srcInfo[2]) - { + if ($issave) { + switch ($srcInfo[2]) { case 1: imagegif($new_img, $toFile); break; case 2: - imagejpeg($new_img, $toFile,100); + imagejpeg($new_img, $toFile, 100); break; case 3: imagepng($new_img, $toFile); @@ -324,14 +316,12 @@ function ImageResizeNew($srcFile, $toW, $toH, $toFile='', $issave=TRUE) imagebmp($new_img, $toFile); break; default: - return FALSE; + return false; } } //不保存 - else - { - switch ($srcInfo[2]) - { + else { + switch ($srcInfo[2]) { case 1: imagegif($new_img); break; @@ -345,11 +335,11 @@ function ImageResizeNew($srcFile, $toW, $toH, $toFile='', $issave=TRUE) imagebmp($new_img); break; default: - return FALSE; + return false; } } imagedestroy($new_img); imagedestroy($img); - return TRUE; + return true; } } diff --git a/include/helpers/mda.helper.php b/include/helpers/mda.helper.php index d3386774..34a1aeae 100755 --- a/include/helpers/mda.helper.php +++ b/include/helpers/mda.helper.php @@ -1,31 +1,31 @@ - $timeout, ), )); - $fp = @fopen($scheme.'://'.$host.':'.$port.$path, 'b', false, $context); + $fp = @fopen($scheme . '://' . $host . ':' . $port . $path, 'b', false, $context); $fpflag = 1; } @@ -101,7 +101,7 @@ function mda_http_send($url, $limit=0, $post='', $cookie='', $timeout=15) $status = stream_get_meta_data($fp); if (!$status['timed_out']) { while (!feof($fp) && !$fpflag) { - if (($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) { + if (($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) { break; } } @@ -116,29 +116,38 @@ function mda_http_send($url, $limit=0, $post='', $cookie='', $timeout=15) } } -function mda_get_setting($skey, $time=false, $real=false) +function mda_get_setting($skey, $time = false, $real = false) { global $dsql; static $setting = array(); - $skey=addslashes($skey); + $skey = addslashes($skey); if (empty($setting[$skey]) || $real) { $row = $dsql->GetOne("SELECT * FROM `#@__plus_mda_setting` WHERE skey='{$skey}'"); - $setting[$skey]['svalue']=$row['svalue']; - $setting[$skey]['stime']=$row['stime']; + $setting[$skey]['svalue'] = $row['svalue']; + $setting[$skey]['stime'] = $row['stime']; + } + if (!isset($setting[$skey])) { + return $time ? array() : null; + } + + if ($skey == 'channel_uuid' and empty($setting[$skey]['svalue'])) { + return '58b78319a0efe'; } - if (!isset($setting[$skey])) return $time ? array() : null; - if ( $skey == 'channel_uuid' AND empty($setting[$skey]['svalue']) ) return '58b78319a0efe'; - if ( $skey == 'channel_secret' AND empty($setting[$skey]['svalue']) ) return 'lDQ97LIb4NXwCV2z'; + + if ($skey == 'channel_secret' and empty($setting[$skey]['svalue'])) { + return 'lDQ97LIb4NXwCV2z'; + } + return $time ? $setting[$skey] : $setting[$skey]['svalue']; } function mda_set_setting($skey, $svalue) { global $dsql; - $stime=time(); - $skey=addslashes($skey); - $svalue=addslashes($svalue); - $sql="UPDATE `#@__plus_mda_setting` SET svalue='{$svalue}',stime='{$stime}' WHERE skey='{$skey}' "; + $stime = time(); + $skey = addslashes($skey); + $svalue = addslashes($svalue); + $sql = "UPDATE `#@__plus_mda_setting` SET svalue='{$svalue}',stime='{$stime}' WHERE skey='{$skey}' "; $dsql->ExecuteNoneQuery($sql); } @@ -146,7 +155,7 @@ function mda_check_islogin() { global $dopost; $jquery_url = MDA_JQUERY; - $mda_login=MDA_API_CHECK_LOGIN; + $mda_login = MDA_API_CHECK_LOGIN; echo << + EOT; //exit; } function mda_islogin() { - if(empty($_SESSION['mda_email'])) { - return FALSE; + if (empty($_SESSION['mda_email'])) { + return false; } $email = mda_get_setting('email'); $channel_uuid = mda_get_setting('channel_uuid'); $channel_secret = mda_get_setting('channel_secret'); - if(empty($email) OR empty($channel_uuid) OR empty($channel_uuid)) { - return FALSE; + if (empty($email) or empty($channel_uuid) or empty($channel_uuid)) { + return false; } - return TRUE; + return true; } -?> diff --git a/include/helpers/smiley.helper.php b/include/helpers/smiley.helper.php index dc676b3b..e7667d2b 100755 --- a/include/helpers/smiley.helper.php +++ b/include/helpers/smiley.helper.php @@ -1,25 +1,22 @@ - $val) - { - $str = str_replace($key, "\"".$cfg_smileys[$key][3]."\"/", $str); - } + foreach ($cfg_smileys as $key => $val) { + $str = str_replace($key, "\""", $str); + } - return $ubb? ubb($str) : $str; - } -} \ No newline at end of file + return $ubb ? ubb($str) : $str; + } +} diff --git a/include/helpers/string.helper.php b/include/helpers/string.helper.php index cb85c281..3de74243 100755 --- a/include/helpers/string.helper.php +++ b/include/helpers/string.helper.php @@ -1,4 +1,4 @@ - $startdd) - { + } else if ($i > $startdd) { $restr .= $c; } - if(ord($str[$i])>0x80) - { - if($str_len>$i+1) - { - $c = $str[$i].$str[$i+1]; + if (ord($str[$i]) > 0x80) { + if ($str_len > $i + 1) { + $c = $str[$i] . $str[$i + 1]; } $i++; - } - else - { + } else { $c = $str[$i]; } - if($i >= $enddd) - { - if(strlen($restr)+strlen($c)>$slen) - { + if ($i >= $enddd) { + if (strlen($restr) + strlen($c) > $slen) { break; - } - else - { + } else { $restr .= $c; break; } @@ -110,12 +93,10 @@ function cn_substr($str, $slen, $startdd=0) * @param int $startdd 开始标记处 * @return string */ -if ( ! function_exists('cn_substr_utf8')) -{ - function cn_substr_utf8($str, $length, $start=0) +if (!function_exists('cn_substr_utf8')) { + function cn_substr_utf8($str, $length, $start = 0) { - if(strlen($str) < $start+1) - { + if (strlen($str) < $start + 1) { return ''; } preg_match_all("/./su", $str, $ar); @@ -123,20 +104,13 @@ function cn_substr_utf8($str, $length, $start=0) $tstr = ''; //为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取 - for($i=0; isset($ar[0][$i]); $i++) - { - if(strlen($tstr) < $start) - { + for ($i = 0;isset($ar[0][$i]); $i++) { + if (strlen($tstr) < $start) { $tstr .= $ar[0][$i]; - } - else - { - if(strlen($str) < $length + strlen($ar[0][$i]) ) - { + } else { + if (strlen($str) < $length + strlen($ar[0][$i])) { $str .= $ar[0][$i]; - } - else - { + } else { break; } } @@ -152,35 +126,28 @@ function cn_substr_utf8($str, $length, $start=0) * @param string $r 如果$r=0直接返回内容,否则需要使用反斜线引用字符串 * @return string */ -if ( ! function_exists('Html2Text')) -{ - function Html2Text($str,$r=0) +if (!function_exists('Html2Text')) { + function Html2Text($str, $r = 0) { - if(!function_exists('SpHtml2Text')) - { - require_once(DEDEINC."/inc/inc_fun_funString.php"); + if (!function_exists('SpHtml2Text')) { + require_once DEDEINC . "/inc/inc_fun_funString.php"; } - if($r==0) - { + if ($r == 0) { return SpHtml2Text($str); - } - else - { + } else { $str = SpHtml2Text(stripslashes($str)); return addslashes($str); } } } - /** * 文本转HTML * * @param string $txt 需要转换的文本内容 * @return string */ -if ( ! function_exists('Text2Html')) -{ +if (!function_exists('Text2Html')) { function Text2Html($txt) { $txt = str_replace(" ", " ", $txt); @@ -197,18 +164,16 @@ function Text2Html($txt) * @param string $fnum 数字字符串 * @return string */ -if ( ! function_exists('GetAlabNum')) -{ +if (!function_exists('GetAlabNum')) { function GetAlabNum($fnum) { - $nums = array("0","1","2","3","4","5","6","7","8","9"); + $nums = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); //$fnums = "0123456789"; - $fnums = array("0","1","2","3","4","5","6","7","8","9"); + $fnums = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); $fnum = str_replace($nums, $fnums, $fnum); $fnum = preg_replace("/[^0-9\.-]/", '', $fnum); - if($fnum=='') - { - $fnum=0; + if ($fnum == '') { + $fnum = 0; } return $fnum; } @@ -223,22 +188,17 @@ function GetAlabNum($fnum) * @param int $isclose 是否关闭字符串资源 * @return string */ -if ( ! function_exists('GetPinyin')) -{ - function GetPinyin($str, $ishead=0, $isclose=1) +if (!function_exists('GetPinyin')) { + function GetPinyin($str, $ishead = 0, $isclose = 1) { global $cfg_soft_lang; - if(!function_exists('SpGetPinyin')) - { + if (!function_exists('SpGetPinyin')) { //全局函数仅是inc_fun_funAdmin.php文件中函数的一个映射 - require_once(DEDEINC."/inc/inc_fun_funAdmin.php"); + require_once DEDEINC . "/inc/inc_fun_funAdmin.php"; } - if($cfg_soft_lang=='utf-8') - { + if ($cfg_soft_lang == 'utf-8') { return SpGetPinyin(utf82gb($str), $ishead, $isclose); - } - else - { + } else { return SpGetPinyin($str, $ishead, $isclose); } } @@ -252,85 +212,83 @@ function GetPinyin($str, $ishead=0, $isclose=1) * @return string */ -if ( ! function_exists('htmlspecialchars_decode')) -{ - function htmlspecialchars_decode($str, $options=ENT_COMPAT) { - $trans = get_html_translation_table(HTML_SPECIALCHARS, $options); +if (!function_exists('htmlspecialchars_decode')) { + function htmlspecialchars_decode($str, $options = ENT_COMPAT) + { + $trans = get_html_translation_table(HTML_SPECIALCHARS, $options); - $decode = ARRAY(); - foreach ($trans AS $char=>$entity) { - $decode[$entity] = $char; - } + $decode = array(); + foreach ($trans as $char => $entity) { + $decode[$entity] = $char; + } - $str = strtr($str, $decode); + $str = strtr($str, $decode); - return $str; - } + return $str; + } } -if ( ! function_exists('ubb')) -{ - function ubb($Text) { - $Text=trim($Text); - //$Text=htmlspecialchars($Text); - //$Text=ereg_replace("\n","
",$Text); - $Text=preg_replace("/\\t/is"," ",$Text); - $Text=preg_replace("/\[hr\]/is","
",$Text); - $Text=preg_replace("/\[separator\]/is","
",$Text); - $Text=preg_replace("/\[h1\](.+?)\[\/h1\]/is","

\\1

",$Text); - $Text=preg_replace("/\[h2\](.+?)\[\/h2\]/is","

\\1

",$Text); - $Text=preg_replace("/\[h3\](.+?)\[\/h3\]/is","

\\1

",$Text); - $Text=preg_replace("/\[h4\](.+?)\[\/h4\]/is","

\\1

",$Text); - $Text=preg_replace("/\[h5\](.+?)\[\/h5\]/is","
\\1
",$Text); - $Text=preg_replace("/\[h6\](.+?)\[\/h6\]/is","
\\1
",$Text); - $Text=preg_replace("/\[center\](.+?)\[\/center\]/is","
\\1
",$Text); - //$Text=preg_replace("/\[url=([^\[]*)\](.+?)\[\/url\]/is","\\2",$Text); - $Text=preg_replace("/\[url\](.+?)\[\/url\]/is","\\1",$Text); - $Text=preg_replace("/\[url=(http:\/\/.+?)\](.+?)\[\/url\]/is","\\2",$Text); - $Text=preg_replace("/\[url=(.+?)\](.+?)\[\/url\]/is","\\2",$Text); - $Text=preg_replace("/\[img\](.+?)\[\/img\]/is","",$Text); - $Text=preg_replace("/\[img\s(.+?)\](.+?)\[\/img\]/is","",$Text); - $Text=preg_replace("/\[color=(.+?)\](.+?)\[\/color\]/is","\\2",$Text); - $Text=preg_replace("/\[style=(.+?)\](.+?)\[\/style\]/is","
\\2
",$Text); - $Text=preg_replace("/\[size=(.+?)\](.+?)\[\/size\]/is","\\2",$Text); - $Text=preg_replace("/\[sup\](.+?)\[\/sup\]/is","\\1",$Text); - $Text=preg_replace("/\[sub\](.+?)\[\/sub\]/is","\\1",$Text); - $Text=preg_replace("/\[pre\](.+?)\[\/pre\]/is","
\\1
",$Text); - if (version_compare(PHP_VERSION, '5.5.0', '>=')) - { - $Text=preg_replace_callback("/\[colorTxt\](.+?)\[\/colorTxt\]/is","color_txt",$Text); - } else { - $Text=preg_replace("/\[colorTxt\](.+?)\[\/colorTxt\]/eis","color_txt('\\1')",$Text); - } - $Text=preg_replace("/\[email\](.+?)\[\/email\]/is","\\1",$Text); - $Text=preg_replace("/\[i\](.+?)\[\/i\]/is","\\1",$Text); - $Text=preg_replace("/\[u\](.+?)\[\/u\]/is","\\1",$Text); - $Text=preg_replace("/\[b\](.+?)\[\/b\]/is","\\1",$Text); - $Text=preg_replace("/\[quote\](.+?)\[\/quote\]/is","
引用:
\\1
", $Text); - $Text=preg_replace("/\[sig\](.+?)\[\/sig\]/is","


--------------------------
\\1
--------------------------
", $Text); - return $Text; - } +if (!function_exists('ubb')) { + function ubb($Text) + { + $Text = trim($Text); + //$Text=htmlspecialchars($Text); + //$Text=ereg_replace("\n","
",$Text); + $Text = preg_replace("/\\t/is", " ", $Text); + $Text = preg_replace("/\[hr\]/is", "
", $Text); + $Text = preg_replace("/\[separator\]/is", "
", $Text); + $Text = preg_replace("/\[h1\](.+?)\[\/h1\]/is", "

\\1

", $Text); + $Text = preg_replace("/\[h2\](.+?)\[\/h2\]/is", "

\\1

", $Text); + $Text = preg_replace("/\[h3\](.+?)\[\/h3\]/is", "

\\1

", $Text); + $Text = preg_replace("/\[h4\](.+?)\[\/h4\]/is", "

\\1

", $Text); + $Text = preg_replace("/\[h5\](.+?)\[\/h5\]/is", "
\\1
", $Text); + $Text = preg_replace("/\[h6\](.+?)\[\/h6\]/is", "
\\1
", $Text); + $Text = preg_replace("/\[center\](.+?)\[\/center\]/is", "
\\1
", $Text); + //$Text=preg_replace("/\[url=([^\[]*)\](.+?)\[\/url\]/is","\\2",$Text); + $Text = preg_replace("/\[url\](.+?)\[\/url\]/is", "\\1", $Text); + $Text = preg_replace("/\[url=(http:\/\/.+?)\](.+?)\[\/url\]/is", "\\2", $Text); + $Text = preg_replace("/\[url=(.+?)\](.+?)\[\/url\]/is", "\\2", $Text); + $Text = preg_replace("/\[img\](.+?)\[\/img\]/is", "", $Text); + $Text = preg_replace("/\[img\s(.+?)\](.+?)\[\/img\]/is", "", $Text); + $Text = preg_replace("/\[color=(.+?)\](.+?)\[\/color\]/is", "\\2", $Text); + $Text = preg_replace("/\[style=(.+?)\](.+?)\[\/style\]/is", "
\\2
", $Text); + $Text = preg_replace("/\[size=(.+?)\](.+?)\[\/size\]/is", "\\2", $Text); + $Text = preg_replace("/\[sup\](.+?)\[\/sup\]/is", "\\1", $Text); + $Text = preg_replace("/\[sub\](.+?)\[\/sub\]/is", "\\1", $Text); + $Text = preg_replace("/\[pre\](.+?)\[\/pre\]/is", "
\\1
", $Text); + if (version_compare(PHP_VERSION, '5.5.0', '>=')) { + $Text = preg_replace_callback("/\[colorTxt\](.+?)\[\/colorTxt\]/is", "color_txt", $Text); + } else { + $Text = preg_replace("/\[colorTxt\](.+?)\[\/colorTxt\]/eis", "color_txt('\\1')", $Text); + } + $Text = preg_replace("/\[email\](.+?)\[\/email\]/is", "\\1", $Text); + $Text = preg_replace("/\[i\](.+?)\[\/i\]/is", "\\1", $Text); + $Text = preg_replace("/\[u\](.+?)\[\/u\]/is", "\\1", $Text); + $Text = preg_replace("/\[b\](.+?)\[\/b\]/is", "\\1", $Text); + $Text = preg_replace("/\[quote\](.+?)\[\/quote\]/is", "
引用:
\\1
", $Text); + $Text = preg_replace("/\[sig\](.+?)\[\/sig\]/is", "


--------------------------
\\1
--------------------------
", $Text); + return $Text; + } } -if ( !function_exists('color_txt') ) -{ - function color_txt($str){ - if ( is_array($str) ) - { +if (!function_exists('color_txt')) { + function color_txt($str) + { + if (is_array($str)) { $str = $str[1]; } - $len = mb_strlen($str); - $colorTxt = ''; - for($i=0; $i<$len; $i++) { - $colorTxt .= ''.mb_substr($str,$i,1,'utf-8').''; + $len = mb_strlen($str); + $colorTxt = ''; + for ($i = 0; $i < $len; $i++) { + $colorTxt .= '' . mb_substr($str, $i, 1, 'utf-8') . ''; } return $colorTxt; } } -if ( !function_exists('rand_color') ) -{ - function rand_color(){ - return '#'.sprintf("%02X",mt_rand(0,255)).sprintf("%02X",mt_rand(0,255)).sprintf("%02X",mt_rand(0,255)); +if (!function_exists('rand_color')) { + function rand_color() + { + return '#' . sprintf("%02X", mt_rand(0, 255)) . sprintf("%02X", mt_rand(0, 255)) . sprintf("%02X", mt_rand(0, 255)); } -} \ No newline at end of file +} diff --git a/include/helpers/test.helper.php b/include/helpers/test.helper.php index c75baec2..1b9fba52 100755 --- a/include/helpers/test.helper.php +++ b/include/helpers/test.helper.php @@ -1,4 +1,4 @@ -$v) - { + foreach ($dt as $k => $v) { $v = preg_replace("/^0{1,}/", '', trim($v)); - if($v=='') - { + if ($v == '') { $dt[$k] = 0; } } $mt = mktime($dt[3], $dt[4], $dt[5], $dt[1], $dt[2], $dt[0]); - if(!empty($mt)) - { - return $mt; - } - else - { - return time(); + if (!empty($mt)) { + return $mt; + } else { + return time(); } } } - /** * 减去时间 * @@ -101,17 +105,15 @@ function GetMkTime($dtime) * @param int $ctime 减少的时间 * @return int */ -if ( ! function_exists('SubDay')) -{ +if (!function_exists('SubDay')) { function SubDay($ntime, $ctime) { $dayst = 3600 * 24; - $cday = ceil(($ntime-$ctime)/$dayst); + $cday = ceil(($ntime - $ctime) / $dayst); return $cday; } } - /** * 增加天数 * @@ -119,8 +121,7 @@ function SubDay($ntime, $ctime) * @param int $aday 增加天数 * @return int */ -if ( ! function_exists('AddDay')) -{ +if (!function_exists('AddDay')) { function AddDay($ntime, $aday) { $dayst = 3600 * 24; @@ -129,18 +130,16 @@ function AddDay($ntime, $aday) } } - /** * 返回格式化(Y-m-d H:i:s)的是时间 * * @param int $mktime 时间戳 * @return string */ -if ( ! function_exists('GetDateTimeMk')) -{ +if (!function_exists('GetDateTimeMk')) { function GetDateTimeMk($mktime) { - return MyDate('Y-m-d H:i:s',$mktime); + return MyDate('Y-m-d H:i:s', $mktime); } } @@ -150,36 +149,52 @@ function GetDateTimeMk($mktime) * @param int $mktime 时间戳 * @return string */ -if ( ! function_exists('GetDateMk')) -{ +if (!function_exists('GetDateMk')) { function GetDateMk($mktime) { - if($mktime=="0") return "暂无"; - else return MyDate("Y-m-d", $mktime); + if ($mktime == "0") { + return "暂无"; + } else { + return MyDate("Y-m-d", $mktime); + } + } } - /** * 将时间转换为距离现在的精确时间 * * @param int $seconds 秒数 * @return string */ -if ( ! function_exists('FloorTime')) -{ +if (!function_exists('FloorTime')) { function FloorTime($seconds) { $times = ''; - $days = floor(($seconds/86400)%30); - $hours = floor(($seconds/3600)%24); - $minutes = floor(($seconds/60)%60); - $seconds = floor($seconds%60); - if($seconds >= 1) $times .= $seconds.'秒'; - if($minutes >= 1) $times = $minutes.'分钟 '.$times; - if($hours >= 1) $times = $hours.'小时 '.$times; - if($days >= 1) $times = $days.'天'; - if($days > 30) return false; + $days = floor(($seconds / 86400) % 30); + $hours = floor(($seconds / 3600) % 24); + $minutes = floor(($seconds / 60) % 60); + $seconds = floor($seconds % 60); + if ($seconds >= 1) { + $times .= $seconds . '秒'; + } + + if ($minutes >= 1) { + $times = $minutes . '分钟 ' . $times; + } + + if ($hours >= 1) { + $times = $hours . '小时 ' . $times; + } + + if ($days >= 1) { + $times = $days . '天'; + } + + if ($days > 30) { + return false; + } + $times .= '前'; return str_replace(" ", '', $times); } diff --git a/include/helpers/upload.helper.php b/include/helpers/upload.helper.php index cb1a049f..25725f10 100755 --- a/include/helpers/upload.helper.php +++ b/include/helpers/upload.helper.php @@ -1,4 +1,4 @@ -getUserID().'-'.dd2char(MyDate('ymdHis', time())).$rnddd; - if($ftype=='imagelit') $filename .= '-L'; - if( file_exists($cfg_basedir.$filedir.'/'.$filename.'.'.$file_sname) ) - { - for($i=50; $i <= 5000; $i++) - { - if( !file_exists($cfg_basedir.$filedir.'/'.$filename.'-'.$i.'.'.$file_sname) ) - { - $filename = $filename.'-'.$i; + $filename = $cuserLogin->getUserID() . '-' . dd2char(MyDate('ymdHis', time())) . $rnddd; + if ($ftype == 'imagelit') { + $filename .= '-L'; + } + + if (file_exists($cfg_basedir . $filedir . '/' . $filename . '.' . $file_sname)) { + for ($i = 50; $i <= 5000; $i++) { + if (!file_exists($cfg_basedir . $filedir . '/' . $filename . '-' . $i . '.' . $file_sname)) { + $filename = $filename . '-' . $i; break; } } } - $fileurl = $filedir.'/'.$filename.'.'.$file_sname; - $rs = move_uploaded_file($file_tmp, $cfg_basedir.$fileurl); - if(!$rs) return -2; - if($ftype=='image' && $watermark) - { - WaterImg($cfg_basedir.$fileurl, 'up'); + $fileurl = $filedir . '/' . $filename . '.' . $file_sname; + $rs = move_uploaded_file($file_tmp, $cfg_basedir . $fileurl); + if (!$rs) { + return -2; } - + + if ($ftype == 'image' && $watermark) { + WaterImg($cfg_basedir . $fileurl, 'up'); + } + //保存信息到数据库 - $title = $filename.'.'.$file_sname; + $title = $filename . '.' . $file_sname; $inquery = "INSERT INTO `#@__uploads`(title,url,mediatype,width,height,playtime,filesize,uptime,mid) - VALUES ('$title','$fileurl','$filetype','0','0','0','".filesize($cfg_basedir.$fileurl)."','".time()."','".$cuserLogin->getUserID()."'); "; + VALUES ('$title','$fileurl','$filetype','0','0','0','" . filesize($cfg_basedir . $fileurl) . "','" . time() . "','" . $cuserLogin->getUserID() . "'); "; $dsql->ExecuteNoneQuery($inquery); $fid = $dsql->GetLastID(); AddMyAddon($fid, $fileurl); @@ -109,132 +119,104 @@ function AdminUpload($uploadname, $ftype='image', $rnddd=0, $watermark=TRUE, $fi } } - //前台会员通用上传函数 //$upname 是文件上传框的表单名,而不是表单的变量 //$handname 允许用户手工指定网址情况下的网址 -if ( ! function_exists('MemberUploads')) -{ - function MemberUploads($upname,$handname,$userid=0,$utype='image',$exname='',$maxwidth=0,$maxheight=0,$water=false,$isadmin=false) +if (!function_exists('MemberUploads')) { + function MemberUploads($upname, $handname, $userid = 0, $utype = 'image', $exname = '', $maxwidth = 0, $maxheight = 0, $water = false, $isadmin = false) { - global $cfg_imgtype,$cfg_mb_addontype,$cfg_mediatype,$cfg_user_dir,$cfg_basedir,$cfg_dir_purview; - + global $cfg_imgtype, $cfg_mb_addontype, $cfg_mediatype, $cfg_user_dir, $cfg_basedir, $cfg_dir_purview; + //当为游客投稿的情况下,这个 id 为 0 - if(empty($userid) ) $userid = 0; - if(!is_dir($cfg_basedir.$cfg_user_dir."/$userid")) - { - MkdirAll($cfg_basedir.$cfg_user_dir."/$userid", $cfg_dir_purview); - CloseFtp(); + if (empty($userid)) { + $userid = 0; + } + + if (!is_dir($cfg_basedir . $cfg_user_dir . "/$userid")) { + MkdirAll($cfg_basedir . $cfg_user_dir . "/$userid", $cfg_dir_purview); + CloseFtp(); } //有上传文件 - $allAllowType = str_replace('||', '|', $cfg_imgtype.'|'.$cfg_mediatype.'|'.$cfg_mb_addontype); - if(!empty($GLOBALS[$upname]) && is_uploaded_file($GLOBALS[$upname])) - { + $allAllowType = str_replace('||', '|', $cfg_imgtype . '|' . $cfg_mediatype . '|' . $cfg_mb_addontype); + if (!empty($GLOBALS[$upname]) && is_uploaded_file($GLOBALS[$upname])) { $nowtme = time(); - $GLOBALS[$upname.'_name'] = trim(preg_replace("#[ \r\n\t\*\%\\\/\?><\|\":]{1,}#",'',$GLOBALS[$upname.'_name'])); + $GLOBALS[$upname . '_name'] = trim(preg_replace("#[ \r\n\t\*\%\\\/\?><\|\":]{1,}#", '', $GLOBALS[$upname . '_name'])); //源文件类型检查 - if($utype=='image') - { - if(!preg_match("/\.(".$cfg_imgtype.")$/", $GLOBALS[$upname.'_name'])) - { - ShowMsg("你所上传的图片类型不在许可列表,请上传{$cfg_imgtype}类型!",'-1'); + if ($utype == 'image') { + if (!preg_match("/\.(" . $cfg_imgtype . ")$/", $GLOBALS[$upname . '_name'])) { + ShowMsg("你所上传的图片类型不在许可列表,请上传{$cfg_imgtype}类型!", '-1'); exit(); } - $sparr = Array("image/pjpeg","image/jpeg","image/gif","image/png","image/xpng","image/wbmp"); - $imgfile_type = strtolower(trim($GLOBALS[$upname.'_type'])); - if(!in_array($imgfile_type, $sparr)) - { + $sparr = array("image/pjpeg", "image/jpeg", "image/gif", "image/png", "image/xpng", "image/wbmp"); + $imgfile_type = strtolower(trim($GLOBALS[$upname . '_type'])); + if (!in_array($imgfile_type, $sparr)) { ShowMsg('上传的图片格式错误,请使用JPEG、GIF、PNG、WBMP格式的其中一种!', '-1'); exit(); } - } - else if($utype=='flash' && !preg_match("/\.swf$/", $GLOBALS[$upname.'_name'])) - { + } else if ($utype == 'flash' && !preg_match("/\.swf$/", $GLOBALS[$upname . '_name'])) { ShowMsg('上传的文件必须为flash文件!', '-1'); exit(); - } - else if($utype=='media' && !preg_match("/\.(".$cfg_mediatype.")$/",$GLOBALS[$upname.'_name'])) - { - ShowMsg('你所上传的文件类型必须为:'.$cfg_mediatype, '-1'); + } else if ($utype == 'media' && !preg_match("/\.(" . $cfg_mediatype . ")$/", $GLOBALS[$upname . '_name'])) { + ShowMsg('你所上传的文件类型必须为:' . $cfg_mediatype, '-1'); exit(); - } - else if(!preg_match("/\.(".$allAllowType.")$/", $GLOBALS[$upname.'_name'])) - { - ShowMsg("你所上传的文件类型不被允许!",'-1'); + } else if (!preg_match("/\.(" . $allAllowType . ")$/", $GLOBALS[$upname . '_name'])) { + ShowMsg("你所上传的文件类型不被允许!", '-1'); exit(); } //再次严格检测文件扩展名是否符合系统定义的类型 - $fs = explode('.', $GLOBALS[$upname.'_name']); - $sname = $fs[count($fs)-1]; + $fs = explode('.', $GLOBALS[$upname . '_name']); + $sname = $fs[count($fs) - 1]; $alltypes = explode('|', $allAllowType); - if(!in_array(strtolower($sname), $alltypes)) - { + if (!in_array(strtolower($sname), $alltypes)) { ShowMsg('你所上传的文件类型不被允许!', '-1'); exit(); } //强制禁止的文件类型 - if(preg_match("/(asp|php|pl|cgi|shtm|js)$/", $sname)) - { + if (preg_match("/(asp|php|pl|cgi|shtm|js)$/", $sname)) { ShowMsg('你上传的文件为系统禁止的类型!', '-1'); exit(); } - if($exname=='') - { - $filename = $cfg_user_dir."/$userid/".dd2char($nowtme.'-'.mt_rand(1000,9999)).'.'.$sname; - } - else - { - $filename = $cfg_user_dir."/{$userid}/{$exname}.".$sname; + if ($exname == '') { + $filename = $cfg_user_dir . "/$userid/" . dd2char($nowtme . '-' . mt_rand(1000, 9999)) . '.' . $sname; + } else { + $filename = $cfg_user_dir . "/{$userid}/{$exname}." . $sname; } - move_uploaded_file($GLOBALS[$upname], $cfg_basedir.$filename) or die("上传文件到 {$filename} 失败!"); + move_uploaded_file($GLOBALS[$upname], $cfg_basedir . $filename) or die("上传文件到 {$filename} 失败!"); @unlink($GLOBALS[$upname]); - - if(@filesize($cfg_basedir.$filename) > $GLOBALS['cfg_mb_upload_size'] * 1024) - { - @unlink($cfg_basedir.$filename); + + if (@filesize($cfg_basedir . $filename) > $GLOBALS['cfg_mb_upload_size'] * 1024) { + @unlink($cfg_basedir . $filename); ShowMsg('你上传的文件超出系统大小限制!', '-1'); exit(); } - + //加水印或缩小图片 - if($utype=='image') - { - include_once(DEDEINC.'/image.func.php'); - if($maxwidth>0 || $maxheight>0) - { - ImageResize($cfg_basedir.$filename, $maxwidth, $maxheight); - } - else if($water) - { - WaterImg($cfg_basedir.$filename); + if ($utype == 'image') { + include_once DEDEINC . '/image.func.php'; + if ($maxwidth > 0 || $maxheight > 0) { + ImageResize($cfg_basedir . $filename, $maxwidth, $maxheight); + } else if ($water) { + WaterImg($cfg_basedir . $filename); } } return $filename; } //没有上传文件 - else - { + else { //强制禁止的文件类型 - if($handname=='') - { + if ($handname == '') { return $handname; - } - else if(preg_match("/\.(asp|php|pl|cgi|shtm|js)$/", $handname)) - { + } else if (preg_match("/\.(asp|php|pl|cgi|shtm|js)$/", $handname)) { exit('Not allow filename for not safe!'); - } - else if( !preg_match("/\.(".$allAllowType.")$/", $handname) ) - { + } else if (!preg_match("/\.(" . $allAllowType . ")$/", $handname)) { exit('Not allow filename for filetype!'); } // 2011-4-10 修复会员中心修改相册时候错误(by:jason123j) - else if( !preg_match('#^http:#', $handname) && !preg_match('#^'.$cfg_user_dir.'/'.$userid."#", $handname) && !$isadmin ) - { + else if (!preg_match('#^http:#', $handname) && !preg_match('#^' . $cfg_user_dir . '/' . $userid . "#", $handname) && !$isadmin) { exit('Not allow filename for not userdir!'); } return $handname; } } } - diff --git a/include/helpers/util.helper.php b/include/helpers/util.helper.php index 68ee43e5..3790f3ae 100755 --- a/include/helpers/util.helper.php +++ b/include/helpers/util.helper.php @@ -1,4 +1,4 @@ -96 && $n<123) || ($n>64 && $n<91) ) - { + for ($i = 0; $i < $slen; $i++) { + if (isset($ddnum[$i + 1])) { + $n = $ddnum[$i] . $ddnum[$i + 1]; + if (($n > 96 && $n < 123) || ($n > 64 && $n < 91)) { $okdd .= chr($n); $i++; - } - else - { + } else { $okdd .= $ddnum[$i]; } - } - else - { + } else { $okdd .= $ddnum[$i]; } } @@ -290,52 +237,52 @@ function dd2char($ddnum) * @return string */ if (!function_exists('json_encode')) { - function format_json_value(&$value) + function format_json_value(&$value) { - if(is_bool($value)) { - $value = $value?'TRUE':'FALSE'; + if (is_bool($value)) { + $value = $value ? 'TRUE' : 'FALSE'; } else if (is_int($value)) { $value = intval($value); } else if (is_float($value)) { $value = floatval($value); - } else if (defined($value) && $value === NULL) { + } else if (defined($value) && $value === null) { $value = strval(constant($value)); } else if (is_string($value)) { - $value = '"'.addslashes($value).'"'; + $value = '"' . addslashes($value) . '"'; } return $value; } function json_encode($data) { - if(is_object($data)) { + if (is_object($data)) { //对象转换成数组 $data = get_object_vars($data); - }else if(!is_array($data)) { + } else if (!is_array($data)) { // 普通格式直接输出 return format_json_value($data); } // 判断是否关联数组 - if(empty($data) || is_numeric(implode('',array_keys($data)))) { - $assoc = FALSE; - }else { - $assoc = TRUE; + if (empty($data) || is_numeric(implode('', array_keys($data)))) { + $assoc = false; + } else { + $assoc = true; } // 组装 Json字符串 - $json = $assoc ? '{' : '[' ; - foreach($data as $key=>$val) { - if(!is_NULL($val)) { - if($assoc) { - $json .= "\"$key\":".json_encode($val).","; - }else { - $json .= json_encode($val).","; + $json = $assoc ? '{' : '['; + foreach ($data as $key => $val) { + if (!is_NULL($val)) { + if ($assoc) { + $json .= "\"$key\":" . json_encode($val) . ","; + } else { + $json .= json_encode($val) . ","; } } } - if(strlen($json)>1) {// 加上判断 防止空数组 - $json = substr($json,0,-1); + if (strlen($json) > 1) { // 加上判断 防止空数组 + $json = substr($json, 0, -1); } - $json .= $assoc ? '}' : ']' ; + $json .= $assoc ? '}' : ']'; return $json; } } @@ -349,30 +296,37 @@ function json_encode($data) * @return string */ if (!function_exists('json_decode')) { - function json_decode($json, $assoc=FALSE) + function json_decode($json, $assoc = false) { // 目前不支持二维数组或对象 - $begin = substr($json,0,1) ; - if(!in_array($begin,array('{','['))) - // 不是对象或者数组直接返回 + $begin = substr($json, 0, 1); + if (!in_array($begin, array('{', '['))) + // 不是对象或者数组直接返回 + { return $json; - $parse = substr($json,1,-1); - $data = explode(',',$parse); - if($flag = $begin =='{' ) { + } + + $parse = substr($json, 1, -1); + $data = explode(',', $parse); + if ($flag = $begin == '{') { // 转换成PHP对象 - $result = new stdClass(); - foreach($data as $val) { - $item = explode(':',$val); - $key = substr($item[0],1,-1); - $result->$key = json_decode($item[1],$assoc); + $result = new stdClass(); + foreach ($data as $val) { + $item = explode(':', $val); + $key = substr($item[0], 1, -1); + $result->$key = json_decode($item[1], $assoc); } - if($assoc) - $result = get_object_vars($result); - }else { + if ($assoc) { + $result = get_object_vars($result); + } + + } else { // 转换成PHP数组 - $result = array(); - foreach($data as $val) - $result[] = json_decode($val,$assoc); + $result = array(); + foreach ($data as $val) { + $result[] = json_decode($val, $assoc); + } + } return $result; } diff --git a/include/helpers/validate.helper.php b/include/helpers/validate.helper.php index efe8834d..cecd8942 100755 --- a/include/helpers/validate.helper.php +++ b/include/helpers/validate.helper.php @@ -1,4 +1,4 @@ -__construct($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpos, $photo_diaphaneity, $photo_wheight, $photo_wwidth, $cfg_watermarktype, $photo_marktrans,$trueMarkimg, $attach); + $this->__construct($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpos, $photo_diaphaneity, $photo_wheight, $photo_wwidth, $cfg_watermarktype, $photo_marktrans, $trueMarkimg, $attach); } // 析构函数 - function __construct($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpos, $photo_diaphaneity, $photo_wheight, $photo_wwidth, $cfg_watermarktype, $photo_marktrans,$trueMarkimg, $attach = array()) + public function __construct($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpos, $photo_diaphaneity, $photo_wheight, $photo_wwidth, $cfg_watermarktype, $photo_marktrans, $trueMarkimg, $attach = array()) { $this->thumbstatus = $cfg_thumb; $this->watermarktext = $cfg_watermarktext; @@ -43,9 +43,7 @@ function __construct($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpo $this->attachinfo = @getimagesize($targetfile); $this->attach = $attach; - - switch($this->attachinfo['mime']) - { + switch ($this->attachinfo['mime']) { case 'image/jpeg': $this->imagecreatefromfunc = function_exists('imagecreatefromjpeg') ? 'imagecreatefromjpeg' : ''; $this->imagefunc = function_exists('imagejpeg') ? 'imagejpeg' : ''; @@ -58,11 +56,10 @@ function __construct($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpo $this->imagecreatefromfunc = function_exists('imagecreatefrompng') ? 'imagecreatefrompng' : ''; $this->imagefunc = function_exists('imagepng') ? 'imagepng' : ''; break; - }//为空则匹配类型的函数不存在 + } //为空则匹配类型的函数不存在 $this->attach['size'] = empty($this->attach['size']) ? @filesize($targetfile) : $this->attach['size']; - if($this->attachinfo['mime'] == 'image/gif') - { + if ($this->attachinfo['mime'] == 'image/gif') { $fp = fopen($targetfile, 'rb'); $targetfilecontent = fread($fp, $this->attach['size']); fclose($fp); @@ -79,12 +76,11 @@ function __construct($targetfile, $cfg_thumb, $cfg_watermarktext, $photo_waterpo * @param int $preview 是否预览 * @return void */ - function thumb($thumbwidth, $thumbheight, $preview = 0) + public function thumb($thumbwidth, $thumbheight, $preview = 0) { $this->thumb_gd($thumbwidth, $thumbheight, $preview); - if($this->thumbstatus == 2 && $this->watermarkstatus) - { + if ($this->thumbstatus == 2 && $this->watermarkstatus) { $this->image($this->targetfile, $this->attach); $this->attach['size'] = filesize($this->targetfile); } @@ -97,11 +93,10 @@ function thumb($thumbwidth, $thumbheight, $preview = 0) * @param int $preview 是否预览 * @return void */ - function watermark($preview = 0) + public function watermark($preview = 0) { - if($this->watermarkminwidth && $this->attachinfo[0] <= $this->watermarkminwidth && $this->watermarkminheight && $this->attachinfo[1] <= $this->watermarkminheight) - { - return ; + if ($this->watermarkminwidth && $this->attachinfo[0] <= $this->watermarkminwidth && $this->watermarkminheight && $this->attachinfo[1] <= $this->watermarkminheight) { + return; } $this->watermark_gd($preview); } @@ -115,38 +110,30 @@ function watermark($preview = 0) * @param int $preview 是否预览 * @return void */ - function thumb_gd($thumbwidth, $thumbheight, $preview = 0) + public function thumb_gd($thumbwidth, $thumbheight, $preview = 0) { - if($this->thumbstatus && function_exists('imagecreatetruecolor') && function_exists('imagecopyresampled') && function_exists('imagejpeg')) - { + if ($this->thumbstatus && function_exists('imagecreatetruecolor') && function_exists('imagecopyresampled') && function_exists('imagejpeg')) { $imagecreatefromfunc = $this->imagecreatefromfunc; $imagefunc = $this->thumbstatus == 1 ? 'imagejpeg' : $this->imagefunc; list($imagewidth, $imageheight) = $this->attachinfo; - if(!$this->animatedgif && ($imagewidth >= $thumbwidth || $imageheight >= $thumbheight)) - { + if (!$this->animatedgif && ($imagewidth >= $thumbwidth || $imageheight >= $thumbheight)) { $attach_photo = $imagecreatefromfunc($this->targetfile); $x_ratio = $thumbwidth / $imagewidth; $y_ratio = $thumbheight / $imageheight; - if(($x_ratio * $imageheight) < $thumbheight) - { + if (($x_ratio * $imageheight) < $thumbheight) { $thumb['height'] = ceil($x_ratio * $imageheight); $thumb['width'] = $thumbwidth; - } - else - { + } else { $thumb['width'] = ceil($y_ratio * $imagewidth); $thumb['height'] = $thumbheight; } - $targetfile = !$preview ? ($this->thumbstatus == 1 ? $this->targetfile.'.thumb.jpg' : $this->targetfile) : './watermark_tmp.jpg'; + $targetfile = !$preview ? ($this->thumbstatus == 1 ? $this->targetfile . '.thumb.jpg' : $this->targetfile) : './watermark_tmp.jpg'; $thumb_photo = imagecreatetruecolor($thumb['width'], $thumb['height']); imagecopyresampled($thumb_photo, $attach_photo, 0, 0, 0, 0, $thumb['width'], $thumb['height'], $imagewidth, $imageheight); - if($this->attachinfo['mime'] == 'image/jpeg') - { + if ($this->attachinfo['mime'] == 'image/jpeg') { $imagefunc($thumb_photo, $targetfile, 100); - } - else - { + } else { $imagefunc($thumb_photo, $targetfile); } $this->attach['thumb'] = $this->thumbstatus == 1 ? 1 : 0; @@ -161,27 +148,22 @@ function thumb_gd($thumbwidth, $thumbheight, $preview = 0) * @param int $preview 是否预览 * @return void */ - function watermark_gd($preview = 0) + public function watermark_gd($preview = 0) { - if($this->watermarkstatus && function_exists('imagecopy') && function_exists('imagealphablending') && function_exists('imagecopymerge')) - { + if ($this->watermarkstatus && function_exists('imagecopy') && function_exists('imagealphablending') && function_exists('imagecopymerge')) { $imagecreatefunc = $this->imagecreatefromfunc; $imagefunc = $this->imagefunc; list($imagewidth, $imageheight) = $this->attachinfo; - if($this->watermarktype < 2) - { - $watermark_file = $this->watermarktype == 1 ? DEDEDATA.'/mark/mark.png' : DEDEDATA.'/mark/mark.gif'; + if ($this->watermarktype < 2) { + $watermark_file = $this->watermarktype == 1 ? DEDEDATA . '/mark/mark.png' : DEDEDATA . '/mark/mark.gif'; $watermarkinfo = @getimagesize($watermark_file); $watermark_logo = $this->watermarktype == 1 ? @imagecreatefrompng($watermark_file) : @imagecreatefromgif($watermark_file); - if(!$watermark_logo) - { - return ; + if (!$watermark_logo) { + return; } list($logowidth, $logoheight) = $watermarkinfo; - } - else - { - $box = @imagettfbbox($this->watermarktext['size'], $this->watermarktext['angle'], $this->watermarktext['fontpath'],$this->watermarktext['text']); + } else { + $box = @imagettfbbox($this->watermarktext['size'], $this->watermarktext['angle'], $this->watermarktext['fontpath'], $this->watermarktext['text']); $logowidth = max($box[2], $box[4]) - min($box[0], $box[6]); $logoheight = max($box[1], $box[3]) - min($box[5], $box[7]); $ax = min($box[0], $box[6]) * -1; @@ -189,10 +171,8 @@ function watermark_gd($preview = 0) } $wmwidth = $imagewidth - $logowidth; $wmheight = $imageheight - $logoheight; - if(($this->watermarktype < 2 && is_readable($watermark_file) || $this->watermarktype == 2) && $wmwidth > 10 && $wmheight > 10 && !$this->animatedgif) - { - switch($this->watermarkstatus) - { + if (($this->watermarktype < 2 && is_readable($watermark_file) || $this->watermarktype == 2) && $wmwidth > 10 && $wmheight > 10 && !$this->animatedgif) { + switch ($this->watermarkstatus) { case 1: $x = +5; @@ -228,47 +208,38 @@ function watermark_gd($preview = 0) break; case 9: $x = $imagewidth - $logowidth - 5; - $y = $imageheight - $logoheight -5; + $y = $imageheight - $logoheight - 5; break; } $dst_photo = @imagecreatetruecolor($imagewidth, $imageheight); $target_photo = $imagecreatefunc($this->targetfile); imagecopy($dst_photo, $target_photo, 0, 0, 0, 0, $imagewidth, $imageheight); - if($this->watermarktype == 1) - { + if ($this->watermarktype == 1) { imagecopy($dst_photo, $watermark_logo, $x, $y, 0, 0, $logowidth, $logoheight); - } - elseif($this->watermarktype == 2) - { - if(($this->watermarktext['shadowx'] || $this->watermarktext['shadowy']) && $this->watermarktext['shadowcolor']) - { + } elseif ($this->watermarktype == 2) { + if (($this->watermarktext['shadowx'] || $this->watermarktext['shadowy']) && $this->watermarktext['shadowcolor']) { $shadowcolorrgb = explode(',', $this->watermarktext['shadowcolor']); $shadowcolor = imagecolorallocate($dst_photo, $shadowcolorrgb[0], $shadowcolorrgb[1], $shadowcolorrgb[2]); imagettftext($dst_photo, $this->watermarktext['size'], $this->watermarktext['angle'], - $x + $ax + $this->watermarktext['shadowx'], $y + $ay + $this->watermarktext['shadowy'], $shadowcolor, - $this->watermarktext['fontpath'], $this->watermarktext['text']); + $x + $ax + $this->watermarktext['shadowx'], $y + $ay + $this->watermarktext['shadowy'], $shadowcolor, + $this->watermarktext['fontpath'], $this->watermarktext['text']); } $colorrgb = explode(',', $this->watermarktext['color']); $color = imagecolorallocate($dst_photo, $colorrgb[0], $colorrgb[1], $colorrgb[2]); imagettftext($dst_photo, $this->watermarktext['size'], $this->watermarktext['angle'], - $x + $ax, $y + $ay, $color, $this->watermarktext['fontpath'], $this->watermarktext['text']); - } - else - { + $x + $ax, $y + $ay, $color, $this->watermarktext['fontpath'], $this->watermarktext['text']); + } else { imagealphablending($watermark_logo, true); imagecopymerge($dst_photo, $watermark_logo, $x, $y, 0, 0, $logowidth, $logoheight, $this->watermarktrans); } $targetfile = !$preview ? $this->targetfile : './watermark_tmp.jpg'; - if($this->attachinfo['mime'] == 'image/jpeg') - { + if ($this->attachinfo['mime'] == 'image/jpeg') { $imagefunc($dst_photo, $targetfile, $this->watermarkquality); - } - else - { + } else { $imagefunc($dst_photo, $targetfile); } $this->attach['size'] = filesize($this->targetfile); } } } -}//End Class \ No newline at end of file +} //End Class diff --git a/include/inc/inc_fun_funAdmin.php b/include/inc/inc_fun_funAdmin.php index 699409e6..06103caf 100755 --- a/include/inc/inc_fun_funAdmin.php +++ b/include/inc/inc_fun_funAdmin.php @@ -1,4 +1,4 @@ -0x80) - { - $c = $str[$i].$str[$i+1]; + for ($i = 0; $i < $slen; $i++) { + if (ord($str[$i]) > 0x80) { + $c = $str[$i] . $str[$i + 1]; $i++; - if(isset($pinyins[$c])) - { - if($ishead==0) - { + if (isset($pinyins[$c])) { + if ($ishead == 0) { $restr .= $pinyins[$c]; - } - else - { + } else { $restr .= $pinyins[$c][0]; } - }else - { + } else { $restr .= "_"; } - }else if( preg_match("/[a-z0-9]/i", $str[$i]) ) - { + } else if (preg_match("/[a-z0-9]/i", $str[$i])) { $restr .= $str[$i]; - } - else - { + } else { $restr .= "_"; } } - if($isclose==0) - { + if ($isclose == 0) { unset($pinyins); } return $restr; } - /** * 创建目录 * @@ -84,37 +69,29 @@ function SpGetPinyin($str, $ishead=0, $isclose=1) */ function SpCreateDir($spath) { - global $cfg_dir_purview,$cfg_basedir,$cfg_ftp_mkdir,$isSafeMode; - if($spath=='') - { + global $cfg_dir_purview, $cfg_basedir, $cfg_ftp_mkdir, $isSafeMode; + if ($spath == '') { return true; } $flink = false; $truepath = $cfg_basedir; - $truepath = str_replace("\\","/",$truepath); - $spaths = explode("/",$spath); + $truepath = str_replace("\\", "/", $truepath); + $spaths = explode("/", $spath); $spath = ""; - foreach($spaths as $spath) - { - if($spath=="") - { + foreach ($spaths as $spath) { + if ($spath == "") { continue; } $spath = trim($spath); - $truepath .= "/".$spath; - if(!is_dir($truepath) || !is_writeable($truepath)) - { - if(!is_dir($truepath)) - { - $isok = MkdirAll($truepath,$cfg_dir_purview); - } - else - { - $isok = ChmodAll($truepath,$cfg_dir_purview); + $truepath .= "/" . $spath; + if (!is_dir($truepath) || !is_writeable($truepath)) { + if (!is_dir($truepath)) { + $isok = MkdirAll($truepath, $cfg_dir_purview); + } else { + $isok = ChmodAll($truepath, $cfg_dir_purview); } - if(!$isok) - { - echo "创建或修改目录:".$truepath." 失败!
"; + if (!$isok) { + echo "创建或修改目录:" . $truepath . " 失败!
"; CloseFtp(); return false; } @@ -126,13 +103,13 @@ function SpCreateDir($spath) function jsScript($js) { - $out = "\n"; + $out = "\n"; - return $out; + return $out; } /** @@ -147,43 +124,34 @@ function jsScript($js) * @param string $isfullpage 是否全屏 * @return string */ -function SpGetEditor($fname,$fvalue,$nheight="350",$etype="Basic",$gtype="print",$isfullpage="false",$bbcode=false) +function SpGetEditor($fname, $fvalue, $nheight = "350", $etype = "Basic", $gtype = "print", $isfullpage = "false", $bbcode = false) { global $cfg_ckeditor_initialized; - if(!isset($GLOBALS['cfg_html_editor'])) - { - $GLOBALS['cfg_html_editor']='fck'; + if (!isset($GLOBALS['cfg_html_editor'])) { + $GLOBALS['cfg_html_editor'] = 'fck'; } - if($gtype=="") - { + if ($gtype == "") { $gtype = "print"; } - if($GLOBALS['cfg_html_editor']=='fck') - { - require_once(DEDEINC.'/FCKeditor/fckeditor.php'); + if ($GLOBALS['cfg_html_editor'] == 'fck') { + require_once DEDEINC . '/FCKeditor/fckeditor.php'; $fck = new FCKeditor($fname); - $fck->BasePath = $GLOBALS['cfg_cmspath'].'/include/FCKeditor/' ; - $fck->Width = '100%' ; - $fck->Height = $nheight ; - $fck->ToolbarSet = $etype ; + $fck->BasePath = $GLOBALS['cfg_cmspath'] . '/include/FCKeditor/'; + $fck->Width = '100%'; + $fck->Height = $nheight; + $fck->ToolbarSet = $etype; $fck->Config['FullPage'] = $isfullpage; - if($GLOBALS['cfg_fck_xhtml']=='Y') - { + if ($GLOBALS['cfg_fck_xhtml'] == 'Y') { $fck->Config['EnableXHTML'] = 'true'; $fck->Config['EnableSourceXHTML'] = 'true'; } - $fck->Value = $fvalue ; - if($gtype=="print") - { + $fck->Value = $fvalue; + if ($gtype == "print") { $fck->Create(); - } - else - { + } else { return $fck->CreateHtml(); } - } - else if($GLOBALS['cfg_html_editor']=='ckeditor') - { + } else if ($GLOBALS['cfg_html_editor'] == 'ckeditor') { $addConfig = ""; if (defined("DEDEADMIN")) { $addConfig = ",{filebrowserImageUploadUrl:'./dialog/select_images_post.php'}"; @@ -195,35 +163,32 @@ function SpGetEditor($fname,$fvalue,$nheight="350",$etype="Basic",$gtype="print" var editor = CKEDITOR.replace('{$fname}'{$addConfig}); EOT; - if($gtype=="print") - { + if ($gtype == "print") { echo $code; - } - else - { + } else { return $code; } - } else { + } else { /* - // ------------------------------------------------------------------------ - // 当前版本,暂时取消dedehtml编辑器的支持 - // ------------------------------------------------------------------------ - require_once(DEDEINC.'/htmledit/dede_editor.php'); - $ded = new DedeEditor($fname); - $ded->BasePath = $GLOBALS['cfg_cmspath'].'/include/htmledit/' ; - $ded->Width = '100%' ; - $ded->Height = $nheight ; - $ded->ToolbarSet = strtolower($etype); - $ded->Value = $fvalue ; - if($gtype=="print") - { - $ded->Create(); - } - else - { - return $ded->CreateHtml(); - } - */ + // ------------------------------------------------------------------------ + // 当前版本,暂时取消dedehtml编辑器的支持 + // ------------------------------------------------------------------------ + require_once(DEDEINC.'/htmledit/dede_editor.php'); + $ded = new DedeEditor($fname); + $ded->BasePath = $GLOBALS['cfg_cmspath'].'/include/htmledit/' ; + $ded->Width = '100%' ; + $ded->Height = $nheight ; + $ded->ToolbarSet = strtolower($etype); + $ded->Value = $fvalue ; + if($gtype=="print") + { + $ded->Create(); + } + else + { + return $ded->CreateHtml(); + } + */ } } @@ -234,12 +199,11 @@ function SpGetEditor($fname,$fvalue,$nheight="350",$etype="Basic",$gtype="print" */ function SpGetNewInfo() { - global $cfg_version,$dsql; + global $cfg_version, $dsql; $nurl = $_SERVER['HTTP_HOST']; - if( preg_match("#[a-z\-]{1,}\.[a-z]{2,}#i",$nurl) ) { + if (preg_match("#[a-z\-]{1,}\.[a-z]{2,}#i", $nurl)) { $nurl = urlencode($nurl); - } - else { + } else { $nurl = "test"; } $phpv = phpversion(); @@ -247,19 +211,21 @@ function SpGetNewInfo() $mysql_ver = $dsql->GetVersion(); $seo_info = $dsql->GetOne("SELECT * FROM `#@__plus_seoinfo` ORDER BY id DESC"); $add_query = ''; - if ( $seo_info ) - { + if ($seo_info) { $add_query .= "&alexa_num={$seo_info['alexa_num']}&alexa_area_num={$seo_info['alexa_area_num']}&baidu_count={$seo_info['baidu_count']}&sogou_count={$seo_info['sogou_count']}&haosou360_count={$seo_info['haosou360_count']}"; } $query = " SELECT COUNT(*) AS dd FROM `#@__member` "; $row1 = $dsql->GetOne($query); - if ( $row1 ) $add_query .= "&mcount={$row1['dd']}"; + if ($row1) { + $add_query .= "&mcount={$row1['dd']}"; + } + $query = " SELECT COUNT(*) AS dd FROM `#@__arctiny` "; $row2 = $dsql->GetOne($query); - if ( $row2 ) $add_query .= "&acount={$row2['dd']}"; - - $offUrl = "http://new"."ver.a"."pi.de"."decms.com/index.php?c=info57&version={$cfg_version}&formurl={$nurl}&phpver={$phpv}&os={$sp_os}&mysqlver={$mysql_ver}{$add_query}"; + if ($row2) { + $add_query .= "&acount={$row2['dd']}"; + } + + $offUrl = "http://new" . "ver.a" . "pi.de" . "decms.com/index.php?c=info57&version={$cfg_version}&formurl={$nurl}&phpver={$phpv}&os={$sp_os}&mysqlver={$mysql_ver}{$add_query}"; return $offUrl; } - -?> \ No newline at end of file diff --git a/include/inc/inc_fun_funString.php b/include/inc/inc_fun_funString.php index 90342c24..cd934b29 100755 --- a/include/inc/inc_fun_funString.php +++ b/include/inc/inc_fun_funString.php @@ -1,37 +1,24 @@ -||/isU","",$str); - $alltext = ""; - $start = 1; - for($i=0;$i") - { - $start = 1; - } - else if($start==1) - { - if($str[$i]=="<") - { - $start = 0; - $alltext .= " "; - } - else if(ord($str[$i])>31) - { - $alltext .= $str[$i]; - } - } - } - $alltext = str_replace(" "," ",$alltext); - $alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext); - $alltext = preg_replace("/[ ]+/s"," ",$alltext); - return $alltext; + $str = preg_replace("/||/isU", "", $str); + $alltext = ""; + $start = 1; + for ($i = 0; $i < strlen($str); $i++) { + if ($start == 0 && $str[$i] == ">") { + $start = 1; + } else if ($start == 1) { + if ($str[$i] == "<") { + $start = 0; + $alltext .= " "; + } else if (ord($str[$i]) > 31) { + $alltext .= $str[$i]; + } + } + } + $alltext = str_replace(" ", " ", $alltext); + $alltext = preg_replace("/&([^;&]*)(;|&)/", "", $alltext); + $alltext = preg_replace("/[ ]+/s", " ", $alltext); + return $alltext; } - -?> \ No newline at end of file diff --git a/include/inc/inc_stat.php b/include/inc/inc_stat.php index ef47e918..c6d03164 100755 --- a/include/inc/inc_stat.php +++ b/include/inc/inc_stat.php @@ -2,19 +2,17 @@ function SpUpdateStat() { global $cfg_version; - if(empty($cfg_version)) - { + if (empty($cfg_version)) { $cfg_version = 'notknow'; } - $statport = array(0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x64,0x65,0x64,0x65, - 0x63,0x6d,0x73,0x2e,0x63,0x6f,0x6d,0x2f,0x73,0x74,0x61,0x74,0x2e,0x70,0x68,0x70, - 0x3f,0x72,0x66,0x68,0x6f,0x73,0x74,0x3d); + $statport = array(0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x64, 0x65, 0x64, 0x65, + 0x63, 0x6d, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x2e, 0x70, 0x68, 0x70, + 0x3f, 0x72, 0x66, 0x68, 0x6f, 0x73, 0x74, 0x3d); $staturl = ''; - foreach($statport as $c) - { + foreach ($statport as $c) { $staturl .= chr($c); } - $staturl = $staturl.urlencode($_SERVER['HTTP_HOST']).'&ver='.urlencode($cfg_version); + $staturl = $staturl . urlencode($_SERVER['HTTP_HOST']) . '&ver=' . urlencode($cfg_version); $stat = @file_get_contents($staturl); return $stat; -} \ No newline at end of file +} diff --git a/include/payment/alipay.php b/include/payment/alipay.php index 349b4ae4..e23f342e 100755 --- a/include/payment/alipay.php +++ b/include/payment/alipay.php @@ -1,13 +1,12 @@ -dsql = $dsql; } - function __construct() + public function __construct() { $this->Alipay(); } - + /** * 设定接口会送地址 * @@ -35,29 +34,30 @@ function __construct() * @param string $returnurl 会送地址 * @return void */ - function SetReturnUrl($returnurl='') + public function SetReturnUrl($returnurl = '') { - if (!empty($returnurl)) - { + if (!empty($returnurl)) { $this->return_url = $returnurl; } } /** - * 生成支付代码 - * @param array $order 订单信息 - * @param array $payment 支付方式信息 - */ - function GetCode($order, $payment) + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + public function GetCode($order, $payment) { - global $cfg_basehost,$cfg_cmspath,$cfg_soft_lang; + global $cfg_basehost, $cfg_cmspath, $cfg_soft_lang; $charset = $cfg_soft_lang; //对于二级目录的处理 - if(!empty($cfg_cmspath)) $cfg_basehost = $cfg_basehost.'/'.$cfg_cmspath; + if (!empty($cfg_cmspath)) { + $cfg_basehost = $cfg_basehost . '/' . $cfg_cmspath; + } $real_method = $payment['alipay_pay_method']; - switch ($real_method){ + switch ($real_method) { case '0': $service = 'trade_create_by_buyer'; break; @@ -70,92 +70,91 @@ function GetCode($order, $payment) } $agent = 'C4335994340215837114'; $parameter = array( - 'agent' => $agent, - 'service' => $service, - 'partner' => $payment['alipay_partner'], - //'partner' => ALIPAY_ID, - '_input_charset' => $charset, - 'notify_url' => $cfg_basehost.$this->return_url."&code=".$payment['code'], - 'return_url' => $cfg_basehost.$this->return_url."&code=".$payment['code'], - /* 业务参数 */ - 'subject' => "支付订单号:".$order['out_trade_no'], - 'out_trade_no' => $order['out_trade_no'], - 'price' => $order['price'], - 'quantity' => 1, - 'payment_type' => 1, - /* 物流参数 */ - 'logistics_type' => 'EXPRESS', - 'logistics_fee' => 0, - 'logistics_payment' => 'BUYER_PAY_AFTER_RECEIVE', - /* 买卖双方信息 */ - 'seller_email' => $payment['alipay_account'] + 'agent' => $agent, + 'service' => $service, + 'partner' => $payment['alipay_partner'], + //'partner' => ALIPAY_ID, + '_input_charset' => $charset, + 'notify_url' => $cfg_basehost . $this->return_url . "&code=" . $payment['code'], + 'return_url' => $cfg_basehost . $this->return_url . "&code=" . $payment['code'], + /* 业务参数 */ + 'subject' => "支付订单号:" . $order['out_trade_no'], + 'out_trade_no' => $order['out_trade_no'], + 'price' => $order['price'], + 'quantity' => 1, + 'payment_type' => 1, + /* 物流参数 */ + 'logistics_type' => 'EXPRESS', + 'logistics_fee' => 0, + 'logistics_payment' => 'BUYER_PAY_AFTER_RECEIVE', + /* 买卖双方信息 */ + 'seller_email' => $payment['alipay_account'], ); ksort($parameter); reset($parameter); $param = ''; - $sign = ''; + $sign = ''; - foreach ($parameter AS $key => $val) - { - $param .= "$key=" .urlencode($val). "&"; - $sign .= "$key=$val&"; + foreach ($parameter as $key => $val) { + $param .= "$key=" . urlencode($val) . "&"; + $sign .= "$key=$val&"; } $param = substr($param, 0, -1); - $sign = substr($sign, 0, -1). $payment['alipay_key']; + $sign = substr($sign, 0, -1) . $payment['alipay_key']; - $button = '
'; + $button = '
'; /* 清空购物车 */ - require_once DEDEINC.'/shopcar.class.php'; - $cart = new MemberShops(); + require_once DEDEINC . '/shopcar.class.php'; + $cart = new MemberShops(); $cart->clearItem(); $cart->MakeOrders(); return $button; } - /** - * 响应操作 - */ - function respond() + * 响应操作 + */ + public function respond() { - if (!empty($_POST)) - { - foreach($_POST as $key => $data) - { + if (!empty($_POST)) { + foreach ($_POST as $key => $data) { $_GET[$key] = $data; } } /* 引入配置文件 */ - $code = preg_replace( "#[^0-9a-z-]#i", "", $_GET['code'] ); - require_once DEDEDATA.'/payment/'.$code.'.php'; - + $code = preg_replace("#[^0-9a-z-]#i", "", $_GET['code']); + require_once DEDEDATA . '/payment/' . $code . '.php'; + /* 取得订单号 */ $order_sn = trim(addslashes($_GET['out_trade_no'])); /*判断订单类型*/ - if(preg_match ("/S-P[0-9]+RN[0-9]/",$order_sn)) { + if (preg_match("/S-P[0-9]+RN[0-9]/", $order_sn)) { //检查支付金额是否相符 $row = $this->dsql->GetOne("SELECT * FROM #@__shops_orders WHERE oid = '{$order_sn}'"); - if ($row['priceCount'] != $_GET['total_fee']) - { + if ($row['priceCount'] != $_GET['total_fee']) { return $msg = "支付失败,支付金额与商品总价不相符!"; } $this->mid = $row['userid']; - $ordertype="goods"; - }else if (preg_match ("/M[0-9]+T[0-9]+RN[0-9]/", $order_sn)){ + $ordertype = "goods"; + } else if (preg_match("/M[0-9]+T[0-9]+RN[0-9]/", $order_sn)) { $row = $this->dsql->GetOne("SELECT * FROM #@__member_operation WHERE buyid = '{$order_sn}'"); //获取订单信息,检查订单的有效性 - if(!is_array($row)||$row['sta']==2) return $msg = "您的订单已经处理,请不要重复提交!"; - elseif($row['money'] != $_GET['total_fee']) return $msg = "支付失败,支付金额与商品总价不相符!"; + if (!is_array($row) || $row['sta'] == 2) { + return $msg = "您的订单已经处理,请不要重复提交!"; + } elseif ($row['money'] != $_GET['total_fee']) { + return $msg = "支付失败,支付金额与商品总价不相符!"; + } + $ordertype = "member"; - $product = $row['product']; - $pname= $row['pname']; - $pid=$row['pid']; + $product = $row['product']; + $pname = $row['pname']; + $pid = $row['pid']; $this->mid = $row['mid']; - } else { + } else { return $msg = "支付失败,您的订单号有问题!"; } @@ -164,129 +163,122 @@ function respond() reset($_GET); $sign = ''; - foreach ($_GET AS $key=>$val) - { - if ($key != 'sign' && $key != 'sign_type' && $key != 'code' && $key != 'dopost') - { + foreach ($_GET as $key => $val) { + if ($key != 'sign' && $key != 'sign_type' && $key != 'code' && $key != 'dopost') { $sign .= "$key=$val&"; } } - $sign = substr($sign, 0, -1).$payment['alipay_key']; + $sign = substr($sign, 0, -1) . $payment['alipay_key']; - if (md5($sign) != $_GET['sign']) - { + if (md5($sign) != $_GET['sign']) { return $msg = "支付失败!"; } - if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'WAIT_SELLER_SEND_GOODS' || $_GET['trade_status'] == 'TRADE_SUCCESS') - { - if($ordertype=="goods"){ - if($this->success_db($order_sn)) return $msg = "支付成功!
返回主页 会员中心"; - else return $msg = "支付失败!
返回主页 会员中心"; - } else if ( $ordertype=="member" ) { - $oldinf = $this->success_mem($order_sn,$pname,$product,$pid); - return $msg = "".$oldinf."
返回主页 会员中心"; + if ($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'WAIT_SELLER_SEND_GOODS' || $_GET['trade_status'] == 'TRADE_SUCCESS') { + if ($ordertype == "goods") { + if ($this->success_db($order_sn)) { + return $msg = "支付成功!
返回主页 会员中心"; + } else { + return $msg = "支付失败!
返回主页 会员中心"; + } + + } else if ($ordertype == "member") { + $oldinf = $this->success_mem($order_sn, $pname, $product, $pid); + return $msg = "" . $oldinf . "
返回主页 会员中心"; } } else { - $this->log_result ("verify_failed"); + $this->log_result("verify_failed"); return $msg = "支付失败!
返回主页 会员中心"; } } /*处理物品交易*/ - function success_db($order_sn) + public function success_db($order_sn) { //获取订单信息,检查订单的有效性 $row = $this->dsql->GetOne("SELECT state FROM #@__shops_orders WHERE oid='$order_sn' "); - if($row['state'] > 0) - { - return TRUE; - } + if ($row['state'] > 0) { + return true; + } /* 改变订单状态_支付成功 */ - $sql = "UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$order_sn' AND `userid`='".$this->mid."'"; - if($this->dsql->ExecuteNoneQuery($sql)) - { - $this->log_result("verify_success,订单号:".$order_sn); //将验证结果存入文件 - return TRUE; + $sql = "UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$order_sn' AND `userid`='" . $this->mid . "'"; + if ($this->dsql->ExecuteNoneQuery($sql)) { + $this->log_result("verify_success,订单号:" . $order_sn); //将验证结果存入文件 + return true; } else { - $this->log_result ("verify_failed,订单号:".$order_sn);//将验证结果存入文件 - return FALSE; + $this->log_result("verify_failed,订单号:" . $order_sn); //将验证结果存入文件 + return false; } } /*处理点卡,会员升级*/ - function success_mem($order_sn,$pname,$product,$pid) + public function success_mem($order_sn, $pname, $product, $pid) { //更新交易状态为已付款 - $sql = "UPDATE `#@__member_operation` SET `sta`='1' WHERE `buyid`='$order_sn' AND `mid`='".$this->mid."'"; + $sql = "UPDATE `#@__member_operation` SET `sta`='1' WHERE `buyid`='$order_sn' AND `mid`='" . $this->mid . "'"; $this->dsql->ExecuteNoneQuery($sql); /* 改变点卡订单状态_支付成功 */ - if($product=="card") - { - $row = $this->dsql->GetOne("SELECT cardid FROM #@__moneycard_record WHERE ctid='$pid' AND isexp='0' ");; + if ($product == "card") { + $row = $this->dsql->GetOne("SELECT cardid FROM #@__moneycard_record WHERE ctid='$pid' AND isexp='0' "); //如果找不到某种类型的卡,直接为用户增加金币 - if(!is_array($row)) - { + if (!is_array($row)) { $nrow = $this->dsql->GetOne("SELECT num FROM #@__moneycard_type WHERE pname = '{$pname}'"); $dnum = $nrow['num']; - $sql1 = "UPDATE `#@__member` SET `money`=money+'{$nrow['num']}' WHERE `mid`='".$this->mid."'"; - $oldinf ="已经充值了".$nrow['num']."金币到您的帐号!"; + $sql1 = "UPDATE `#@__member` SET `money`=money+'{$nrow['num']}' WHERE `mid`='" . $this->mid . "'"; + $oldinf = "已经充值了" . $nrow['num'] . "金币到您的帐号!"; } else { $cardid = $row['cardid']; - $sql1=" UPDATE #@__moneycard_record SET uid='".$this->mid."',isexp='1',utime='".time()."' WHERE cardid='$cardid' "; - $oldinf='您的充值密码是:'.$cardid.''; + $sql1 = " UPDATE #@__moneycard_record SET uid='" . $this->mid . "',isexp='1',utime='" . time() . "' WHERE cardid='$cardid' "; + $oldinf = '您的充值密码是:' . $cardid . ''; } //更新交易状态为已关闭 - $sql2=" UPDATE #@__member_operation SET sta=2,oldinfo='$oldinf' WHERE buyid='$order_sn'"; - if($this->dsql->ExecuteNoneQuery($sql1) && $this->dsql->ExecuteNoneQuery($sql2)) - { - $this->log_result("verify_success,订单号:".$order_sn); //将验证结果存入文件 + $sql2 = " UPDATE #@__member_operation SET sta=2,oldinfo='$oldinf' WHERE buyid='$order_sn'"; + if ($this->dsql->ExecuteNoneQuery($sql1) && $this->dsql->ExecuteNoneQuery($sql2)) { + $this->log_result("verify_success,订单号:" . $order_sn); //将验证结果存入文件 return $oldinf; } else { - $this->log_result ("verify_failed,订单号:".$order_sn);//将验证结果存入文件 + $this->log_result("verify_failed,订单号:" . $order_sn); //将验证结果存入文件 return "支付失败!"; } - /* 改变会员订单状态_支付成功 */ - } else if ( $product=="member" ){ + /* 改变会员订单状态_支付成功 */ + } else if ($product == "member") { $row = $this->dsql->GetOne("SELECT rank,exptime FROM #@__member_type WHERE aid='$pid' "); $rank = $row['rank']; $exptime = $row['exptime']; /*计算原来升级剩余的天数*/ - $rs = $this->dsql->GetOne("SELECT uptime,exptime FROM #@__member WHERE mid='".$this->mid."'"); - if($rs['uptime']!=0 && $rs['exptime']!=0 ) - { + $rs = $this->dsql->GetOne("SELECT uptime,exptime FROM #@__member WHERE mid='" . $this->mid . "'"); + if ($rs['uptime'] != 0 && $rs['exptime'] != 0) { $nowtime = time(); - $mhasDay = $rs['exptime'] - ceil(($nowtime - $rs['uptime'])/3600/24) + 1; - $mhasDay=($mhasDay>0)? $mhasDay : 0; + $mhasDay = $rs['exptime'] - ceil(($nowtime - $rs['uptime']) / 3600 / 24) + 1; + $mhasDay = ($mhasDay > 0) ? $mhasDay : 0; } //获取会员默认级别的金币和积分数 $memrank = $this->dsql->GetOne("SELECT money,scores FROM #@__arcrank WHERE rank='$rank'"); //更新会员信息 - $sql1 = " UPDATE #@__member SET rank='$rank',money=money+'{$memrank['money']}', - scores=scores+'{$memrank['scores']}',exptime='$exptime'+'$mhasDay',uptime='".time()."' - WHERE mid='".$this->mid."'"; + $sql1 = " UPDATE #@__member SET rank='$rank',money=money+'{$memrank['money']}', + scores=scores+'{$memrank['scores']}',exptime='$exptime'+'$mhasDay',uptime='" . time() . "' + WHERE mid='" . $this->mid . "'"; //更新交易状态为已关闭 - $sql2=" UPDATE #@__member_operation SET sta='2',oldinfo='会员升级成功!' WHERE buyid='$order_sn' "; - if($this->dsql->ExecuteNoneQuery($sql1) && $this->dsql->ExecuteNoneQuery($sql2)) - { - $this->log_result("verify_success,订单号:".$order_sn); //将验证结果存入文件 + $sql2 = " UPDATE #@__member_operation SET sta='2',oldinfo='会员升级成功!' WHERE buyid='$order_sn' "; + if ($this->dsql->ExecuteNoneQuery($sql1) && $this->dsql->ExecuteNoneQuery($sql2)) { + $this->log_result("verify_success,订单号:" . $order_sn); //将验证结果存入文件 return "会员升级成功!"; } else { - $this->log_result ("verify_failed,订单号:".$order_sn);//将验证结果存入文件 + $this->log_result("verify_failed,订单号:" . $order_sn); //将验证结果存入文件 return "会员升级失败!"; } - } + } } - function log_result($word) + public function log_result($word) { global $cfg_cmspath; - $fp = fopen(dirname(__FILE__)."/../../data/payment/log.txt","a"); - flock($fp, LOCK_EX) ; - fwrite($fp,$word.",执行日期:".strftime("%Y-%m-%d %H:%I:%S",time())."\r\n"); + $fp = fopen(dirname(__FILE__) . "/../../data/payment/log.txt", "a"); + flock($fp, LOCK_EX); + fwrite($fp, $word . ",执行日期:" . strftime("%Y-%m-%d %H:%I:%S", time()) . "\r\n"); flock($fp, LOCK_UN); fclose($fp); } -}//End API \ No newline at end of file +} //End API diff --git a/include/payment/bank.php b/include/payment/bank.php index acba5413..236dbf23 100755 --- a/include/payment/bank.php +++ b/include/payment/bank.php @@ -1,5 +1,4 @@ -bank(); + $this->bank(); } - + /** - * 设置回送地址 - */ - - function SetReturnUrl($returnurl='') + * 设置回送地址 + */ + + public function SetReturnUrl($returnurl = '') { return ""; } /** - * 提交函数 - */ - function GetCode($order,$payment) + * 提交函数 + */ + public function GetCode($order, $payment) { - require_once DEDEINC.'/shopcar.class.php'; + require_once DEDEINC . '/shopcar.class.php'; $cart = new MemberShops(); $cart->clearItem(); $cart->MakeOrders(); - if($payment=="member") $button="您可以 返回首页 或去 会员中心"; - else $button="您可以 返回首页 或去 查看订单"; + if ($payment == "member") { + $button = "您可以 返回首页 或去 会员中心"; + } else { + $button = "您可以 返回首页 或去 查看订单"; + } + return $button; } - -}//End API \ No newline at end of file + +} //End API diff --git a/include/payment/cod.php b/include/payment/cod.php index ffe9cb8c..2b3e453c 100755 --- a/include/payment/cod.php +++ b/include/payment/cod.php @@ -1,5 +1,4 @@ -Cod(); } /** - * 设置回送地址 - */ - - function SetReturnUrl($returnurl='') + * 设置回送地址 + */ + + public function SetReturnUrl($returnurl = '') { return ""; } - + /** - * 获取代码 - */ - function GetCode($order) + * 获取代码 + */ + public function GetCode($order) { - require_once DEDEINC.'/shopcar.class.php'; + require_once DEDEINC . '/shopcar.class.php'; $cart = new MemberShops(); $cart->clearItem(); $cart->MakeOrders(); - $button="您可以 返回首页 或去 查看订单"; - return $button; + $button = "您可以 返回首页 或去 查看订单"; + return $button; } -}//End API \ No newline at end of file +} //End API diff --git a/include/payment/yeepay.php b/include/payment/yeepay.php index 93208d22..95a7f8ff 100755 --- a/include/payment/yeepay.php +++ b/include/payment/yeepay.php @@ -1,46 +1,45 @@ -dsql = $dsql; } - function __construct() + public function __construct() { $this->yeepay(); } - + /** * 设定接口会送地址 * @@ -49,376 +48,382 @@ function __construct() * @param string $returnurl 会送地址 * @return void */ - function SetReturnUrl($returnurl='') + public function SetReturnUrl($returnurl = '') { - if (!empty($returnurl)) - { + if (!empty($returnurl)) { $this->return_url = $returnurl; } } /** - * 生成支付代码 - * @param array $order 订单信息 - * @param array $payment 支付方式信息 - */ - function GetCode($order, $payment) + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + public function GetCode($order, $payment) { - global $cfg_basehost,$cfg_cmspath; + global $cfg_basehost, $cfg_cmspath; //对于二级目录的处理 - if(!empty($cfg_cmspath)) $cfg_basehost = $cfg_basehost.'/'.$cfg_cmspath; + if (!empty($cfg_cmspath)) { + $cfg_basehost = $cfg_basehost . '/' . $cfg_cmspath; + } # 商家设置用户购买商品的支付信息. ##易宝支付平台统一使用GBK/GB2312编码方式,参数如用到中文,请注意转码 - + # 商户订单号,选填. ##若不为"",提交的订单号必须在自身账户交易中唯一;为""时,易宝支付会自动生成随机的商户订单号. - $p2_Order = trim($order['out_trade_no']); - + $p2_Order = trim($order['out_trade_no']); + # 支付金额,必填. ##单位:元,精确到分. - $p3_Amt = $order['price']; - + $p3_Amt = $order['price']; + # 交易币种,固定值"CNY". - $p4_Cur = "CNY"; - + $p4_Cur = "CNY"; + # 商品名称 ##用于支付时显示在易宝支付网关左侧的订单产品信息. - $p5_Pid = trim($order['out_trade_no']); - + $p5_Pid = trim($order['out_trade_no']); + # 商品种类 - $p6_Pcat = 'cart'; - + $p6_Pcat = 'cart'; + # 商品描述 - $p7_Pdesc = ''; - + $p7_Pdesc = ''; + # 商户接收支付成功数据的地址,支付成功后易宝支付会向该地址发送两次成功通知. - //$p8_Url = $cfg_basehost."/plus/carbuyaction.php?dopost=return&code=".$payment['code']; - $p8_Url = $cfg_basehost.$this->return_url.'&code='.$payment['code']; - + //$p8_Url = $cfg_basehost."/plus/carbuyaction.php?dopost=return&code=".$payment['code']; + $p8_Url = $cfg_basehost . $this->return_url . '&code=' . $payment['code']; + # 商户扩展信息 - ##商户可以任意填写1K 的字符串,支付成功时将原样返回. - $pa_MP = 'member'; - + ##商户可以任意填写1K 的字符串,支付成功时将原样返回. + $pa_MP = 'member'; + # 应答机制 ##为"1": 需要应答机制;为"0": 不需要应答机制. - $pr_NeedResponse = 1; - + $pr_NeedResponse = 1; + # 银行编码 - ##默认为"",到易宝支付网关.若不需显示易宝支付的页面,直接跳转到各银行、神州行支付、骏网一卡通等支付页面,该字段可依照附录:银行列表设置参数值. - $pd_FrpId = ''; + ##默认为"",到易宝支付网关.若不需显示易宝支付的页面,直接跳转到各银行、神州行支付、骏网一卡通等支付页面,该字段可依照附录:银行列表设置参数值. + $pd_FrpId = ''; #调用签名函数生成签名串 - $hmac = $this->getReqHmacString($payment['yp_account'],$payment['yp_key'],$p2_Order,$p3_Amt,$p4_Cur,$p5_Pid,$p6_Pcat,$p7_Pdesc,$p8_Url,$pa_MP,$pd_FrpId,$pr_NeedResponse); - - $button = '
- - - - - - - - - - - - - - + $hmac = $this->getReqHmacString($payment['yp_account'], $payment['yp_key'], $p2_Order, $p3_Amt, $p4_Cur, $p5_Pid, $p6_Pcat, $p7_Pdesc, $p8_Url, $pa_MP, $pd_FrpId, $pr_NeedResponse); + + $button = ' + + + + + + + + + + + + + +
'; - /* 清空购物车 */ - require_once DEDEINC.'/shopcar.class.php'; - $cart = new MemberShops(); + /* 清空购物车 */ + require_once DEDEINC . '/shopcar.class.php'; + $cart = new MemberShops(); $cart->clearItem(); $cart->MakeOrders(); return $button; } /** - * 响应操作 - */ - function respond() + * 响应操作 + */ + public function respond() { /* 引入配置文件 */ - $code = preg_replace( "#[^0-9a-z-]#i", "", $_REQUEST['code'] ); - require_once DEDEDATA.'/payment/'.$code.'.php'; - + $code = preg_replace("#[^0-9a-z-]#i", "", $_REQUEST['code']); + require_once DEDEDATA . '/payment/' . $code . '.php'; + $p1_MerId = trim($payment['yp_account']); $merchantKey = trim($payment['yp_key']); - + # 解析返回参数. $return = $this->getCallBackValue($r0_Cmd, $r1_Code, $r2_TrxId, $r3_Amt, $r4_Cur, $r5_Pid, $r6_Order, $r7_Uid, $r8_MP, $r9_BType, $hmac); - + # 判断返回签名是否正确(True/False) - $bRet = $this->CheckHmac($p1_MerId,$merchantKey,$r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType,$hmac); + $bRet = $this->CheckHmac($p1_MerId, $merchantKey, $r0_Cmd, $r1_Code, $r2_TrxId, $r3_Amt, $r4_Cur, $r5_Pid, $r6_Order, $r7_Uid, $r8_MP, $r9_BType, $hmac); # 校验码正确. - if($bRet) - { - if($r1_Code=="1") - { + if ($bRet) { + if ($r1_Code == "1") { /*判断订单类型*/ - if(preg_match ("/S-P[0-9]+RN[0-9]/",$r6_Order)) - { + if (preg_match("/S-P[0-9]+RN[0-9]/", $r6_Order)) { //获取用户mid $row = $this->dsql->GetOne("SELECT * FROM #@__shops_orders WHERE oid = '{$r6_Order}'"); $this->mid = $row['userid']; - $ordertype="goods"; - } else if (preg_match ("/M[0-9]+T[0-9]+RN[0-9]/",$r6_Order)){ + $ordertype = "goods"; + } else if (preg_match("/M[0-9]+T[0-9]+RN[0-9]/", $r6_Order)) { $row = $this->dsql->GetOne("SELECT * FROM #@__member_operation WHERE buyid = '{$r6_Order}'"); //获取订单信息,检查订单的有效性 - if(!is_array($row)||$row['sta']==2) return $msg = "您的订单已经处理,请不要重复提交!"; + if (!is_array($row) || $row['sta'] == 2) { + return $msg = "您的订单已经处理,请不要重复提交!"; + } + $ordertype = "member"; - $product = $row['product']; - $pname= $row['pname']; - $pid=$row['pid']; + $product = $row['product']; + $pname = $row['pname']; + $pid = $row['pid']; $this->mid = $row['mid']; - } else { + } else { return $msg = "支付失败,您的订单号有问题!"; } - # 需要比较返回的金额与商家数据库中订单的金额是否相等,只有相等的情况下才认为是交易成功. - # 并且需要对返回的处理进行事务控制,进行记录的排它性处理,防止对同一条交易重复发货的情况发生. - if($r9_BType == "1" || $r9_BType == "3"){ - if($ordertype == "goods"){ - if($this->success_db($r6_Order)) return $msg = "支付成功!
返回主页 会员中心"; - else return $msg = "支付失败!
返回主页 会员中心"; - } else if ($ordertype=="member") { - $oldinf = $this->success_mem($r6_Order,$pname,$product,$pid); - return $msg = "".$oldinf."
返回主页 会员中心"; + # 并且需要对返回的处理进行事务控制,进行记录的排它性处理,防止对同一条交易重复发货的情况发生. + if ($r9_BType == "1" || $r9_BType == "3") { + if ($ordertype == "goods") { + if ($this->success_db($r6_Order)) { + return $msg = "支付成功!
返回主页 会员中心"; + } else { + return $msg = "支付失败!
返回主页 会员中心"; + } + + } else if ($ordertype == "member") { + $oldinf = $this->success_mem($r6_Order, $pname, $product, $pid); + return $msg = "" . $oldinf . "
返回主页 会员中心"; } - } else if ( $r9_BType == "2" ){ + } else if ($r9_BType == "2") { #如果需要应答机制则必须回写流,以success开头,大小写不敏感. echo "success"; - if($ordertype=="goods"){ - if($this->success_db($r6_Order)) return $msg = "支付成功!
返回主页 会员中心"; - else return $msg = "支付失败!
返回主页 会员中心"; - } else if ($ordertype=="member") { - if($this->success_mem($r6_Order,$pname,$product,$pid)) return $msg = "支付成功!
返回主页 会员中心"; - else return $msg = "支付失败!
返回主页 会员中心"; + if ($ordertype == "goods") { + if ($this->success_db($r6_Order)) { + return $msg = "支付成功!
返回主页 会员中心"; + } else { + return $msg = "支付失败!
返回主页 会员中心"; + } + + } else if ($ordertype == "member") { + if ($this->success_mem($r6_Order, $pname, $product, $pid)) { + return $msg = "支付成功!
返回主页 会员中心"; + } else { + return $msg = "支付失败!
返回主页 会员中心"; + } + } } } } else { - $this->log_result ("verify_failed"); + $this->log_result("verify_failed"); return $msg = "交易信息被篡!
返回主页 "; } } - #签名函数生成签名串 - function getReqHmacString($p1_MerId,$merchantKey,$p2_Order,$p3_Amt,$p4_Cur,$p5_Pid,$p6_Pcat,$p7_Pdesc,$p8_Url,$pa_MP,$pd_FrpId,$pr_NeedResponse) + public function getReqHmacString($p1_MerId, $merchantKey, $p2_Order, $p3_Amt, $p4_Cur, $p5_Pid, $p6_Pcat, $p7_Pdesc, $p8_Url, $pa_MP, $pd_FrpId, $pr_NeedResponse) { #进行签名处理,一定按照文档中标明的签名顺序进行 $sbOld = ""; #加入业务类型 - $sbOld = $sbOld.$this->p0_Cmd; + $sbOld = $sbOld . $this->p0_Cmd; #加入商户编号 - $sbOld = $sbOld.$p1_MerId; + $sbOld = $sbOld . $p1_MerId; #加入商户订单号 - $sbOld = $sbOld.$p2_Order; + $sbOld = $sbOld . $p2_Order; #加入支付金额 - $sbOld = $sbOld.$p3_Amt; + $sbOld = $sbOld . $p3_Amt; #加入交易币种 - $sbOld = $sbOld.$p4_Cur; + $sbOld = $sbOld . $p4_Cur; #加入商品名称 - $sbOld = $sbOld.$p5_Pid; + $sbOld = $sbOld . $p5_Pid; #加入商品分类 - $sbOld = $sbOld.$p6_Pcat; + $sbOld = $sbOld . $p6_Pcat; #加入商品描述 - $sbOld = $sbOld.$p7_Pdesc; + $sbOld = $sbOld . $p7_Pdesc; #加入商户接收支付成功数据的地址 - $sbOld = $sbOld.$p8_Url; + $sbOld = $sbOld . $p8_Url; #加入送货地址标识 - $sbOld = $sbOld.$this->p9_SAF; + $sbOld = $sbOld . $this->p9_SAF; #加入商户扩展信息 - $sbOld = $sbOld.$pa_MP; + $sbOld = $sbOld . $pa_MP; #加入银行编码 - $sbOld = $sbOld.$pd_FrpId; + $sbOld = $sbOld . $pd_FrpId; #加入是否需要应答机制 - $sbOld = $sbOld.$pr_NeedResponse; - - return $this->HmacMd5($sbOld,$merchantKey); - } + $sbOld = $sbOld . $pr_NeedResponse; + + return $this->HmacMd5($sbOld, $merchantKey); + } # 取得返回串中的所有参数 - function getCallBackValue(&$r0_Cmd,&$r1_Code,&$r2_TrxId,&$r3_Amt,&$r4_Cur,&$r5_Pid,&$r6_Order,&$r7_Uid,&$r8_MP,&$r9_BType,&$hmac) - { - $r0_Cmd = $_REQUEST['r0_Cmd']; - $r1_Code = $_REQUEST['r1_Code']; - $r2_TrxId = $_REQUEST['r2_TrxId']; - $r3_Amt = $_REQUEST['r3_Amt']; - $r4_Cur = $_REQUEST['r4_Cur']; - $r5_Pid = $_REQUEST['r5_Pid']; - $r6_Order = $_REQUEST['r6_Order']; - $r7_Uid = $_REQUEST['r7_Uid']; - $r8_MP = $_REQUEST['r8_MP']; - $r9_BType = $_REQUEST['r9_BType']; - $hmac = $_REQUEST['hmac']; - return NULL; + public function getCallBackValue(&$r0_Cmd, &$r1_Code, &$r2_TrxId, &$r3_Amt, &$r4_Cur, &$r5_Pid, &$r6_Order, &$r7_Uid, &$r8_MP, &$r9_BType, &$hmac) + { + $r0_Cmd = $_REQUEST['r0_Cmd']; + $r1_Code = $_REQUEST['r1_Code']; + $r2_TrxId = $_REQUEST['r2_TrxId']; + $r3_Amt = $_REQUEST['r3_Amt']; + $r4_Cur = $_REQUEST['r4_Cur']; + $r5_Pid = $_REQUEST['r5_Pid']; + $r6_Order = $_REQUEST['r6_Order']; + $r7_Uid = $_REQUEST['r7_Uid']; + $r8_MP = $_REQUEST['r8_MP']; + $r9_BType = $_REQUEST['r9_BType']; + $hmac = $_REQUEST['hmac']; + return null; } - function CheckHmac($p1_MerId,$merchantKey,$r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType,$hmac) + public function CheckHmac($p1_MerId, $merchantKey, $r0_Cmd, $r1_Code, $r2_TrxId, $r3_Amt, $r4_Cur, $r5_Pid, $r6_Order, $r7_Uid, $r8_MP, $r9_BType, $hmac) { - if($hmac == $this->getCallbackHmacString($p1_MerId,$merchantKey,$r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType)) - return TRUE; - else - return FALSE; + if ($hmac == $this->getCallbackHmacString($p1_MerId, $merchantKey, $r0_Cmd, $r1_Code, $r2_TrxId, $r3_Amt, $r4_Cur, $r5_Pid, $r6_Order, $r7_Uid, $r8_MP, $r9_BType)) { + return true; + } else { + return false; + } + } - function getCallbackHmacString($p1_MerId,$merchantKey,$r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType) + public function getCallbackHmacString($p1_MerId, $merchantKey, $r0_Cmd, $r1_Code, $r2_TrxId, $r3_Amt, $r4_Cur, $r5_Pid, $r6_Order, $r7_Uid, $r8_MP, $r9_BType) { #取得加密前的字符串 $sbOld = ""; #加入商家ID - $sbOld = $sbOld.$p1_MerId; + $sbOld = $sbOld . $p1_MerId; #加入消息类型 - $sbOld = $sbOld.$r0_Cmd; + $sbOld = $sbOld . $r0_Cmd; #加入业务返回码 - $sbOld = $sbOld.$r1_Code; + $sbOld = $sbOld . $r1_Code; #加入交易ID - $sbOld = $sbOld.$r2_TrxId; + $sbOld = $sbOld . $r2_TrxId; #加入交易金额 - $sbOld = $sbOld.$r3_Amt; + $sbOld = $sbOld . $r3_Amt; #加入货币单位 - $sbOld = $sbOld.$r4_Cur; + $sbOld = $sbOld . $r4_Cur; #加入产品Id - $sbOld = $sbOld.$r5_Pid; + $sbOld = $sbOld . $r5_Pid; #加入订单ID - $sbOld = $sbOld.$r6_Order; + $sbOld = $sbOld . $r6_Order; #加入用户ID - $sbOld = $sbOld.$r7_Uid; + $sbOld = $sbOld . $r7_Uid; #加入商家扩展信息 - $sbOld = $sbOld.$r8_MP; + $sbOld = $sbOld . $r8_MP; #加入交易结果返回类型 - $sbOld = $sbOld.$r9_BType; - - return $this->HmacMd5($sbOld,$merchantKey,'gbk'); + $sbOld = $sbOld . $r9_BType; + + return $this->HmacMd5($sbOld, $merchantKey, 'gbk'); } - function HmacMd5($data,$key,$lang='utf-8') + public function HmacMd5($data, $key, $lang = 'utf-8') { // RFC 2104 HMAC implementation for php. // Creates an md5 HMAC. // Eliminates the need to install mhash to compute a HMAC // Hacked by Lance Rushing(NOTE: Hacked means written) - + //需要配置环境支持iconv,否则中文参数不能正常处理 - if($GLOBALS['cfg_soft_lang'] != 'utf-8' || $lang!='utf-8') - { + if ($GLOBALS['cfg_soft_lang'] != 'utf-8' || $lang != 'utf-8') { $key = gb2utf8($key); $data = gb2utf8($data); } $b = 64; // byte length for md5 if (strlen($key) > $b) { - $key = pack("H*",md5($key)); + $key = pack("H*", md5($key)); } $key = str_pad($key, $b, chr(0x00)); $ipad = str_pad('', $b, chr(0x36)); $opad = str_pad('', $b, chr(0x5c)); - $k_ipad = $key ^ $ipad ; + $k_ipad = $key ^ $ipad; $k_opad = $key ^ $opad; - - return md5($k_opad . pack("H*",md5($k_ipad . $data))); + + return md5($k_opad . pack("H*", md5($k_ipad . $data))); } /*处理物品交易*/ - function success_db($order_sn) + public function success_db($order_sn) { //获取订单信息,检查订单的有效性 $row = $this->dsql->GetOne("SELECT state FROM #@__shops_orders WHERE oid='$order_sn' "); - if($row['state'] > 0) - { - return TRUE; - } + if ($row['state'] > 0) { + return true; + } /* 改变订单状态_支付成功 */ - $sql = "UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$order_sn' AND `userid`='".$this->mid."'"; - if($this->dsql->ExecuteNoneQuery($sql)) - { - $this->log_result("verify_success,订单号:".$order_sn); //将验证结果存入文件 - return TRUE; + $sql = "UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$order_sn' AND `userid`='" . $this->mid . "'"; + if ($this->dsql->ExecuteNoneQuery($sql)) { + $this->log_result("verify_success,订单号:" . $order_sn); //将验证结果存入文件 + return true; } else { - $this->log_result ("verify_failed,订单号:".$order_sn);//将验证结果存入文件 - return FALSE; + $this->log_result("verify_failed,订单号:" . $order_sn); //将验证结果存入文件 + return false; } } /*处理点卡,会员升级*/ - function success_mem($order_sn,$pname,$product,$pid) + public function success_mem($order_sn, $pname, $product, $pid) { //更新交易状态为已付款 - $sql = "UPDATE `#@__member_operation` SET `sta`='1' WHERE `buyid`='$order_sn' AND `mid`='".$this->mid."'"; + $sql = "UPDATE `#@__member_operation` SET `sta`='1' WHERE `buyid`='$order_sn' AND `mid`='" . $this->mid . "'"; $this->dsql->ExecuteNoneQuery($sql); /* 改变点卡订单状态_支付成功 */ - if($product=="card") - { - $row = $this->dsql->GetOne("SELECT cardid FROM #@__moneycard_record WHERE ctid='$pid' AND isexp='0' ");; + if ($product == "card") { + $row = $this->dsql->GetOne("SELECT cardid FROM #@__moneycard_record WHERE ctid='$pid' AND isexp='0' "); //如果找不到某种类型的卡,直接为用户增加金币 - if(!is_array($row)) - { + if (!is_array($row)) { $nrow = $this->dsql->GetOne("SELECT num FROM #@__moneycard_type WHERE pname = '{$pname}'"); $dnum = $nrow['num']; - $sql1 = "UPDATE `#@__member` SET `money`=money+'{$nrow['num']}' WHERE `mid`='".$this->mid."'"; - $oldinf ="已经充值了".$nrow['num']."金币到您的帐号!"; + $sql1 = "UPDATE `#@__member` SET `money`=money+'{$nrow['num']}' WHERE `mid`='" . $this->mid . "'"; + $oldinf = "已经充值了" . $nrow['num'] . "金币到您的帐号!"; } else { $cardid = $row['cardid']; - $sql1=" UPDATE #@__moneycard_record SET uid='".$this->mid."',isexp='1',utime='".time()."' WHERE cardid='$cardid' "; - $oldinf='您的充值密码是:'.$cardid.''; + $sql1 = " UPDATE #@__moneycard_record SET uid='" . $this->mid . "',isexp='1',utime='" . time() . "' WHERE cardid='$cardid' "; + $oldinf = '您的充值密码是:' . $cardid . ''; } //更新交易状态为已关闭 - $sql2=" UPDATE #@__member_operation SET sta=2,oldinfo='$oldinf' WHERE buyid='$order_sn'"; - if($this->dsql->ExecuteNoneQuery($sql1) && $this->dsql->ExecuteNoneQuery($sql2)) - { - $this->log_result("verify_success,订单号:".$order_sn); //将验证结果存入文件 + $sql2 = " UPDATE #@__member_operation SET sta=2,oldinfo='$oldinf' WHERE buyid='$order_sn'"; + if ($this->dsql->ExecuteNoneQuery($sql1) && $this->dsql->ExecuteNoneQuery($sql2)) { + $this->log_result("verify_success,订单号:" . $order_sn); //将验证结果存入文件 return $oldinf; } else { - $this->log_result ("verify_failed,订单号:".$order_sn);//将验证结果存入文件 + $this->log_result("verify_failed,订单号:" . $order_sn); //将验证结果存入文件 return "支付失败!"; } - /* 改变会员订单状态_支付成功 */ - } else if ( $product=="member" ){ + /* 改变会员订单状态_支付成功 */ + } else if ($product == "member") { $row = $this->dsql->GetOne("SELECT rank,exptime FROM #@__member_type WHERE aid='$pid' "); $rank = $row['rank']; $exptime = $row['exptime']; /*计算原来升级剩余的天数*/ - $rs = $this->dsql->GetOne("SELECT uptime,exptime FROM #@__member WHERE mid='".$this->mid."'"); - if($rs['uptime']!=0 && $rs['exptime']!=0 ) - { + $rs = $this->dsql->GetOne("SELECT uptime,exptime FROM #@__member WHERE mid='" . $this->mid . "'"); + if ($rs['uptime'] != 0 && $rs['exptime'] != 0) { $nowtime = time(); - $mhasDay = $rs['exptime'] - ceil(($nowtime - $rs['uptime'])/3600/24) + 1; - $mhasDay=($mhasDay>0)? $mhasDay : 0; + $mhasDay = $rs['exptime'] - ceil(($nowtime - $rs['uptime']) / 3600 / 24) + 1; + $mhasDay = ($mhasDay > 0) ? $mhasDay : 0; } //获取会员默认级别的金币和积分数 $memrank = $this->dsql->GetOne("SELECT money,scores FROM #@__arcrank WHERE rank='$rank'"); //更新会员信息 - $sql1 = " UPDATE #@__member SET rank='$rank',money=money+'{$memrank['money']}', - scores=scores+'{$memrank['scores']}',exptime='$exptime'+'$mhasDay',uptime='".time()."' - WHERE mid='".$this->mid."'"; + $sql1 = " UPDATE #@__member SET rank='$rank',money=money+'{$memrank['money']}', + scores=scores+'{$memrank['scores']}',exptime='$exptime'+'$mhasDay',uptime='" . time() . "' + WHERE mid='" . $this->mid . "'"; //更新交易状态为已关闭 - $sql2=" UPDATE #@__member_operation SET sta='2',oldinfo='会员升级成功!' WHERE buyid='$order_sn' "; - if($this->dsql->ExecuteNoneQuery($sql1) && $this->dsql->ExecuteNoneQuery($sql2)) - { - $this->log_result("verify_success,订单号:".$order_sn); //将验证结果存入文件 + $sql2 = " UPDATE #@__member_operation SET sta='2',oldinfo='会员升级成功!' WHERE buyid='$order_sn' "; + if ($this->dsql->ExecuteNoneQuery($sql1) && $this->dsql->ExecuteNoneQuery($sql2)) { + $this->log_result("verify_success,订单号:" . $order_sn); //将验证结果存入文件 return "会员升级成功!"; } else { - $this->log_result ("verify_failed,订单号:".$order_sn);//将验证结果存入文件 + $this->log_result("verify_failed,订单号:" . $order_sn); //将验证结果存入文件 return "会员升级失败!"; } - } + } } - function log_result($word) { + public function log_result($word) + { global $cfg_cmspath; - $fp = fopen(dirname(__FILE__)."/../../data/payment/log.txt","a"); - flock($fp, LOCK_EX) ; - fwrite($fp,$word.",执行日期:".strftime("%Y-%m-%d %H:%I:%S",time())."\r\n"); + $fp = fopen(dirname(__FILE__) . "/../../data/payment/log.txt", "a"); + flock($fp, LOCK_EX); + fwrite($fp, $word . ",执行日期:" . strftime("%Y-%m-%d %H:%I:%S", time()) . "\r\n"); flock($fp, LOCK_UN); fclose($fp); } -}//End API \ No newline at end of file +} //End API diff --git a/include/qrcode/phpqrcode.php b/include/qrcode/phpqrcode.php index ea8c08f9..b5c7431a 100755 --- a/include/qrcode/phpqrcode.php +++ b/include/qrcode/phpqrcode.php @@ -32,22 +32,14 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - /* * Version: 1.1.4 * Build: 2010100721 */ - - //---- qrconst.php ----------------------------- - - - - /* * PHP QR Code encoder * @@ -73,64 +65,55 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - // Encoding modes - - define('QR_MODE_NUL', -1); - define('QR_MODE_NUM', 0); - define('QR_MODE_AN', 1); - define('QR_MODE_8', 2); - define('QR_MODE_KANJI', 3); - define('QR_MODE_STRUCTURE', 4); - - // Levels of error correction. - - define('QR_ECLEVEL_L', 0); - define('QR_ECLEVEL_M', 1); - define('QR_ECLEVEL_Q', 2); - define('QR_ECLEVEL_H', 3); - - // Supported output formats - - define('QR_FORMAT_TEXT', 0); - define('QR_FORMAT_PNG', 1); - - class qrstr { - public static function set(&$srctab, $x, $y, $repl, $replLen = false) { - $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); - } - } +// Encoding modes +define('QR_MODE_NUL', -1); +define('QR_MODE_NUM', 0); +define('QR_MODE_AN', 1); +define('QR_MODE_8', 2); +define('QR_MODE_KANJI', 3); +define('QR_MODE_STRUCTURE', 4); -//---- merged_config.php ----------------------------- +// Levels of error correction. + +define('QR_ECLEVEL_L', 0); +define('QR_ECLEVEL_M', 1); +define('QR_ECLEVEL_Q', 2); +define('QR_ECLEVEL_H', 3); +// Supported output formats +define('QR_FORMAT_TEXT', 0); +define('QR_FORMAT_PNG', 1); +class qrstr +{ + public static function set(&$srctab, $x, $y, $repl, $replLen = false) + { + $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false) ? substr($repl, 0, $replLen) : $repl, $x, ($replLen !== false) ? $replLen : strlen($repl)); + } +} + +//---- merged_config.php ----------------------------- /* * PHP QR Code encoder * * Config file, tuned-up for merged verion */ - - define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there - define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true - define('QR_LOG_DIR', false); // default error logs dir - - define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code - define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly - define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false - - define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images - - +define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there +define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true +define('QR_LOG_DIR', false); // default error logs dir -//---- qrtools.php ----------------------------- - +define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code +define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly +define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false +define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images +//---- qrtools.php ----------------------------- /* * PHP QR Code encoder @@ -155,161 +138,162 @@ public static function set(&$srctab, $x, $y, $repl, $replLen = false) { * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - class QRtools { - - //---------------------------------------------------------------------- - public static function binarize($frame) - { - $len = count($frame); - foreach ($frame as &$frameLine) { - - for($i=0; $i<$len; $i++) { - $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0'; - } +class QRtools +{ + + //---------------------------------------------------------------------- + public static function binarize($frame) + { + $len = count($frame); + foreach ($frame as &$frameLine) { + + for ($i = 0; $i < $len; $i++) { + $frameLine[$i] = (ord($frameLine[$i]) & 1) ? '1' : '0'; } - - return $frame; - } - - //---------------------------------------------------------------------- - public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') - { - $barcode_array = array(); - - if (!is_array($mode)) - $mode = explode(',', $mode); - - $eccLevel = 'L'; - - if (count($mode) > 1) { - $eccLevel = $mode[1]; - } - - $qrTab = QRcode::text($code, false, $eccLevel); - $size = count($qrTab); - - $barcode_array['num_rows'] = $size; - $barcode_array['num_cols'] = $size; - $barcode_array['bcode'] = array(); - - foreach ($qrTab as $line) { - $arrAdd = array(); - foreach(str_split($line) as $char) - $arrAdd[] = ($char=='1')?1:0; - $barcode_array['bcode'][] = $arrAdd; - } - - return $barcode_array; - } - - //---------------------------------------------------------------------- - public static function clearCache() - { - self::$frames = array(); - } - - //---------------------------------------------------------------------- - public static function buildCache() - { - QRtools::markTime('before_build_cache'); - - $mask = new QRmask(); - for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) { - $frame = QRspec::newFrame($a); - if (QR_IMAGE) { - $fileName = QR_CACHE_DIR.'frame_'.$a.'.png'; - QRimage::png(self::binarize($frame), $fileName, 1, 0); - } - - $width = count($frame); - $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); - for ($maskNo=0; $maskNo<8; $maskNo++) - $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); - } - - QRtools::markTime('after_build_cache'); - } - - //---------------------------------------------------------------------- - public static function log($outfile, $err) - { - if (QR_LOG_DIR !== false) { - if ($err != '') { - if ($outfile !== false) { - file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); - } else { - file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); - } - } + } + + return $frame; + } + + //---------------------------------------------------------------------- + public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') + { + $barcode_array = array(); + + if (!is_array($mode)) { + $mode = explode(',', $mode); + } + + $eccLevel = 'L'; + + if (count($mode) > 1) { + $eccLevel = $mode[1]; + } + + $qrTab = QRcode::text($code, false, $eccLevel); + $size = count($qrTab); + + $barcode_array['num_rows'] = $size; + $barcode_array['num_cols'] = $size; + $barcode_array['bcode'] = array(); + + foreach ($qrTab as $line) { + $arrAdd = array(); + foreach (str_split($line) as $char) { + $arrAdd[] = ($char == '1') ? 1 : 0; } + + $barcode_array['bcode'][] = $arrAdd; } - - //---------------------------------------------------------------------- - public static function dumpMask($frame) - { + + return $barcode_array; + } + + //---------------------------------------------------------------------- + public static function clearCache() + { + self::$frames = array(); + } + + //---------------------------------------------------------------------- + public static function buildCache() + { + QRtools::markTime('before_build_cache'); + + $mask = new QRmask(); + for ($a = 1; $a <= QRSPEC_VERSION_MAX; $a++) { + $frame = QRspec::newFrame($a); + if (QR_IMAGE) { + $fileName = QR_CACHE_DIR . 'frame_' . $a . '.png'; + QRimage::png(self::binarize($frame), $fileName, 1, 0); + } + $width = count($frame); - for($y=0;$y<$width;$y++) { - for($x=0;$x<$width;$x++) { - echo ord($frame[$y][$x]).','; - } + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + for ($maskNo = 0; $maskNo < 8; $maskNo++) { + $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); } + } - - //---------------------------------------------------------------------- - public static function markTime($markerId) - { - list($usec, $sec) = explode(" ", microtime()); - $time = ((float)$usec + (float)$sec); - - if (!isset($GLOBALS['qr_time_bench'])) - $GLOBALS['qr_time_bench'] = array(); - - $GLOBALS['qr_time_bench'][$markerId] = $time; - } - - //---------------------------------------------------------------------- - public static function timeBenchmark() - { - self::markTime('finish'); - - $lastTime = 0; - $startTime = 0; - $p = 0; - - echo ' - - '; - foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) { - if ($p > 0) { - echo ''; + QRtools::markTime('after_build_cache'); + } + + //---------------------------------------------------------------------- + public static function log($outfile, $err) + { + if (QR_LOG_DIR !== false) { + if ($err != '') { + if ($outfile !== false) { + file_put_contents(QR_LOG_DIR . basename($outfile) . '-errors.txt', date('Y-m-d H:i:s') . ': ' . $err, FILE_APPEND); } else { - $startTime = $thisTime; + file_put_contents(QR_LOG_DIR . 'errors.txt', date('Y-m-d H:i:s') . ': ' . $err, FILE_APPEND); } - - $p++; - $lastTime = $thisTime; } - - echo ' - - -
BENCHMARK
till '.$markerId.': '.number_format($thisTime-$lastTime, 6).'s
TOTAL: '.number_format($lastTime-$startTime, 6).'s
'; } - } - - //########################################################################## - - QRtools::markTime('start'); - + //---------------------------------------------------------------------- + public static function dumpMask($frame) + { + $width = count($frame); + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { + echo ord($frame[$y][$x]) . ','; + } + } + } + + //---------------------------------------------------------------------- + public static function markTime($markerId) + { + list($usec, $sec) = explode(" ", microtime()); + $time = ((float) $usec + (float) $sec); + if (!isset($GLOBALS['qr_time_bench'])) { + $GLOBALS['qr_time_bench'] = array(); + } -//---- qrspec.php ----------------------------- + $GLOBALS['qr_time_bench'][$markerId] = $time; + } + + //---------------------------------------------------------------------- + public static function timeBenchmark() + { + self::markTime('finish'); + + $lastTime = 0; + $startTime = 0; + $p = 0; + + echo ' + + '; + + foreach ($GLOBALS['qr_time_bench'] as $markerId => $thisTime) { + if ($p > 0) { + echo ''; + } else { + $startTime = $thisTime; + } + + $p++; + $lastTime = $thisTime; + } + + echo ' + + +
BENCHMARK
till ' . $markerId . ': ' . number_format($thisTime - $lastTime, 6) . 's
TOTAL: ' . number_format($lastTime - $startTime, 6) . 's
'; + } +} +//########################################################################## +QRtools::markTime('start'); + +//---- qrspec.php ----------------------------- /* * PHP QR Code encoder @@ -325,7 +309,7 @@ public static function timeBenchmark() * The following data / specifications are taken from * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) * or - * "Automatic identification and data capture techniques -- + * "Automatic identification and data capture techniques -- * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) * * This library is free software; you can redistribute it and/or @@ -342,498 +326,506 @@ public static function timeBenchmark() * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('QRSPEC_VERSION_MAX', 40); - define('QRSPEC_WIDTH_MAX', 177); - - define('QRCAP_WIDTH', 0); - define('QRCAP_WORDS', 1); - define('QRCAP_REMINDER', 2); - define('QRCAP_EC', 3); - - class QRspec { - - public static $capacity = array( - array( 0, 0, 0, array( 0, 0, 0, 0)), - array( 21, 26, 0, array( 7, 10, 13, 17)), // 1 - array( 25, 44, 7, array( 10, 16, 22, 28)), - array( 29, 70, 7, array( 15, 26, 36, 44)), - array( 33, 100, 7, array( 20, 36, 52, 64)), - array( 37, 134, 7, array( 26, 48, 72, 88)), // 5 - array( 41, 172, 7, array( 36, 64, 96, 112)), - array( 45, 196, 0, array( 40, 72, 108, 130)), - array( 49, 242, 0, array( 48, 88, 132, 156)), - array( 53, 292, 0, array( 60, 110, 160, 192)), - array( 57, 346, 0, array( 72, 130, 192, 224)), //10 - array( 61, 404, 0, array( 80, 150, 224, 264)), - array( 65, 466, 0, array( 96, 176, 260, 308)), - array( 69, 532, 0, array( 104, 198, 288, 352)), - array( 73, 581, 3, array( 120, 216, 320, 384)), - array( 77, 655, 3, array( 132, 240, 360, 432)), //15 - array( 81, 733, 3, array( 144, 280, 408, 480)), - array( 85, 815, 3, array( 168, 308, 448, 532)), - array( 89, 901, 3, array( 180, 338, 504, 588)), - array( 93, 991, 3, array( 196, 364, 546, 650)), - array( 97, 1085, 3, array( 224, 416, 600, 700)), //20 - array(101, 1156, 4, array( 224, 442, 644, 750)), - array(105, 1258, 4, array( 252, 476, 690, 816)), - array(109, 1364, 4, array( 270, 504, 750, 900)), - array(113, 1474, 4, array( 300, 560, 810, 960)), - array(117, 1588, 4, array( 312, 588, 870, 1050)), //25 - array(121, 1706, 4, array( 336, 644, 952, 1110)), - array(125, 1828, 4, array( 360, 700, 1020, 1200)), - array(129, 1921, 3, array( 390, 728, 1050, 1260)), - array(133, 2051, 3, array( 420, 784, 1140, 1350)), - array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30 - array(141, 2323, 3, array( 480, 868, 1290, 1530)), - array(145, 2465, 3, array( 510, 924, 1350, 1620)), - array(149, 2611, 3, array( 540, 980, 1440, 1710)), - array(153, 2761, 3, array( 570, 1036, 1530, 1800)), - array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35 - array(161, 3034, 0, array( 600, 1120, 1680, 1980)), - array(165, 3196, 0, array( 630, 1204, 1770, 2100)), - array(169, 3362, 0, array( 660, 1260, 1860, 2220)), - array(173, 3532, 0, array( 720, 1316, 1950, 2310)), - array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40 - ); - - //---------------------------------------------------------------------- - public static function getDataLength($version, $level) - { - return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; - } - - //---------------------------------------------------------------------- - public static function getECCLength($version, $level) - { - return self::$capacity[$version][QRCAP_EC][$level]; - } - - //---------------------------------------------------------------------- - public static function getWidth($version) - { - return self::$capacity[$version][QRCAP_WIDTH]; - } - - //---------------------------------------------------------------------- - public static function getRemainder($version) - { - return self::$capacity[$version][QRCAP_REMINDER]; - } - - //---------------------------------------------------------------------- - public static function getMinimumVersion($size, $level) - { - - for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) { - $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; - if($words >= $size) - return $i; + +define('QRSPEC_VERSION_MAX', 40); +define('QRSPEC_WIDTH_MAX', 177); + +define('QRCAP_WIDTH', 0); +define('QRCAP_WORDS', 1); +define('QRCAP_REMINDER', 2); +define('QRCAP_EC', 3); + +class QRspec +{ + + public static $capacity = array( + array(0, 0, 0, array(0, 0, 0, 0)), + array(21, 26, 0, array(7, 10, 13, 17)), // 1 + array(25, 44, 7, array(10, 16, 22, 28)), + array(29, 70, 7, array(15, 26, 36, 44)), + array(33, 100, 7, array(20, 36, 52, 64)), + array(37, 134, 7, array(26, 48, 72, 88)), // 5 + array(41, 172, 7, array(36, 64, 96, 112)), + array(45, 196, 0, array(40, 72, 108, 130)), + array(49, 242, 0, array(48, 88, 132, 156)), + array(53, 292, 0, array(60, 110, 160, 192)), + array(57, 346, 0, array(72, 130, 192, 224)), //10 + array(61, 404, 0, array(80, 150, 224, 264)), + array(65, 466, 0, array(96, 176, 260, 308)), + array(69, 532, 0, array(104, 198, 288, 352)), + array(73, 581, 3, array(120, 216, 320, 384)), + array(77, 655, 3, array(132, 240, 360, 432)), //15 + array(81, 733, 3, array(144, 280, 408, 480)), + array(85, 815, 3, array(168, 308, 448, 532)), + array(89, 901, 3, array(180, 338, 504, 588)), + array(93, 991, 3, array(196, 364, 546, 650)), + array(97, 1085, 3, array(224, 416, 600, 700)), //20 + array(101, 1156, 4, array(224, 442, 644, 750)), + array(105, 1258, 4, array(252, 476, 690, 816)), + array(109, 1364, 4, array(270, 504, 750, 900)), + array(113, 1474, 4, array(300, 560, 810, 960)), + array(117, 1588, 4, array(312, 588, 870, 1050)), //25 + array(121, 1706, 4, array(336, 644, 952, 1110)), + array(125, 1828, 4, array(360, 700, 1020, 1200)), + array(129, 1921, 3, array(390, 728, 1050, 1260)), + array(133, 2051, 3, array(420, 784, 1140, 1350)), + array(137, 2185, 3, array(450, 812, 1200, 1440)), //30 + array(141, 2323, 3, array(480, 868, 1290, 1530)), + array(145, 2465, 3, array(510, 924, 1350, 1620)), + array(149, 2611, 3, array(540, 980, 1440, 1710)), + array(153, 2761, 3, array(570, 1036, 1530, 1800)), + array(157, 2876, 0, array(570, 1064, 1590, 1890)), //35 + array(161, 3034, 0, array(600, 1120, 1680, 1980)), + array(165, 3196, 0, array(630, 1204, 1770, 2100)), + array(169, 3362, 0, array(660, 1260, 1860, 2220)), + array(173, 3532, 0, array(720, 1316, 1950, 2310)), + array(177, 3706, 0, array(750, 1372, 2040, 2430)), //40 + ); + + //---------------------------------------------------------------------- + public static function getDataLength($version, $level) + { + return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getECCLength($version, $level) + { + return self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getWidth($version) + { + return self::$capacity[$version][QRCAP_WIDTH]; + } + + //---------------------------------------------------------------------- + public static function getRemainder($version) + { + return self::$capacity[$version][QRCAP_REMINDER]; + } + + //---------------------------------------------------------------------- + public static function getMinimumVersion($size, $level) + { + + for ($i = 1; $i <= QRSPEC_VERSION_MAX; $i++) { + $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; + if ($words >= $size) { + return $i; } - return -1; } - - //###################################################################### - - public static $lengthTableBits = array( - array(10, 12, 14), - array( 9, 11, 13), - array( 8, 16, 16), - array( 8, 10, 12) + + return -1; + } + + //###################################################################### + + public static $lengthTableBits = array( + array(10, 12, 14), + array(9, 11, 13), + array(8, 16, 16), + array(8, 10, 12), + ); + + //---------------------------------------------------------------------- + public static function lengthIndicator($mode, $version) + { + if ($mode == QR_MODE_STRUCTURE) { + return 0; + } + + if ($version <= 9) { + $l = 0; + } else if ($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + return self::$lengthTableBits[$mode][$l]; + } + + //---------------------------------------------------------------------- + public static function maximumWords($mode, $version) + { + if ($mode == QR_MODE_STRUCTURE) { + return 3; + } + + if ($version <= 9) { + $l = 0; + } else if ($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + $bits = self::$lengthTableBits[$mode][$l]; + $words = (1 << $bits) - 1; + + if ($mode == QR_MODE_KANJI) { + $words *= 2; // the number of bytes is required + } + + return $words; + } + + // Error correction code ----------------------------------------------- + // Table of the error correction code (Reed-Solomon block) + // See Table 12-16 (pp.30-36), JIS X0510:2004. + + public static $eccTable = array( + array(array(0, 0), array(0, 0), array(0, 0), array(0, 0)), + array(array(1, 0), array(1, 0), array(1, 0), array(1, 0)), // 1 + array(array(1, 0), array(1, 0), array(1, 0), array(1, 0)), + array(array(1, 0), array(1, 0), array(2, 0), array(2, 0)), + array(array(1, 0), array(2, 0), array(2, 0), array(4, 0)), + array(array(1, 0), array(2, 0), array(2, 2), array(2, 2)), // 5 + array(array(2, 0), array(4, 0), array(4, 0), array(4, 0)), + array(array(2, 0), array(4, 0), array(2, 4), array(4, 1)), + array(array(2, 0), array(2, 2), array(4, 2), array(4, 2)), + array(array(2, 0), array(3, 2), array(4, 4), array(4, 4)), + array(array(2, 2), array(4, 1), array(6, 2), array(6, 2)), //10 + array(array(4, 0), array(1, 4), array(4, 4), array(3, 8)), + array(array(2, 2), array(6, 2), array(4, 6), array(7, 4)), + array(array(4, 0), array(8, 1), array(8, 4), array(12, 4)), + array(array(3, 1), array(4, 5), array(11, 5), array(11, 5)), + array(array(5, 1), array(5, 5), array(5, 7), array(11, 7)), //15 + array(array(5, 1), array(7, 3), array(15, 2), array(3, 13)), + array(array(1, 5), array(10, 1), array(1, 15), array(2, 17)), + array(array(5, 1), array(9, 4), array(17, 1), array(2, 19)), + array(array(3, 4), array(3, 11), array(17, 4), array(9, 16)), + array(array(3, 5), array(3, 13), array(15, 5), array(15, 10)), //20 + array(array(4, 4), array(17, 0), array(17, 6), array(19, 6)), + array(array(2, 7), array(17, 0), array(7, 16), array(34, 0)), + array(array(4, 5), array(4, 14), array(11, 14), array(16, 14)), + array(array(6, 4), array(6, 14), array(11, 16), array(30, 2)), + array(array(8, 4), array(8, 13), array(7, 22), array(22, 13)), //25 + array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), + array(array(8, 4), array(22, 3), array(8, 26), array(12, 28)), + array(array(3, 10), array(3, 23), array(4, 31), array(11, 31)), + array(array(7, 7), array(21, 7), array(1, 37), array(19, 26)), + array(array(5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 + array(array(13, 3), array(2, 29), array(42, 1), array(23, 28)), + array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), + array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), + array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), + array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 + array(array(6, 14), array(6, 34), array(46, 10), array(2, 64)), + array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), + array(array(4, 18), array(13, 32), array(48, 14), array(42, 32)), + array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), + array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)), //40 + ); + + //---------------------------------------------------------------------- + // CACHEABLE!!! + + public static function getEccSpec($version, $level, array &$spec) + { + if (count($spec) < 5) { + $spec = array(0, 0, 0, 0, 0); + } + + $b1 = self::$eccTable[$version][$level][0]; + $b2 = self::$eccTable[$version][$level][1]; + $data = self::getDataLength($version, $level); + $ecc = self::getECCLength($version, $level); + + if ($b2 == 0) { + $spec[0] = $b1; + $spec[1] = (int) ($data / $b1); + $spec[2] = (int) ($ecc / $b1); + $spec[3] = 0; + $spec[4] = 0; + } else { + $spec[0] = $b1; + $spec[1] = (int) ($data / ($b1 + $b2)); + $spec[2] = (int) ($ecc / ($b1 + $b2)); + $spec[3] = $b2; + $spec[4] = $spec[1] + 1; + } + } + + // Alignment pattern --------------------------------------------------- + + // Positions of alignment patterns. + // This array includes only the second and the third position of the + // alignment patterns. Rest of them can be calculated from the distance + // between them. + + // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. + + public static $alignmentPattern = array( + array(0, 0), + array(0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 + array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 + array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 + array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 + array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 + array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 + array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 + array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 + ); + + /** -------------------------------------------------------------------- + * Put an alignment marker. + * @param frame + * @param width + * @param ox,oy center coordinate of the pattern + */ + public static function putAlignmentMarker(array &$frame, $ox, $oy) + { + $finder = array( + "\xa1\xa1\xa1\xa1\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa0\xa1\xa0\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa1\xa1\xa1\xa1", ); - - //---------------------------------------------------------------------- - public static function lengthIndicator($mode, $version) - { - if ($mode == QR_MODE_STRUCTURE) - return 0; - - if ($version <= 9) { - $l = 0; - } else if ($version <= 26) { - $l = 1; - } else { - $l = 2; - } - - return self::$lengthTableBits[$mode][$l]; - } - - //---------------------------------------------------------------------- - public static function maximumWords($mode, $version) - { - if($mode == QR_MODE_STRUCTURE) - return 3; - - if($version <= 9) { - $l = 0; - } else if($version <= 26) { - $l = 1; - } else { - $l = 2; - } - - $bits = self::$lengthTableBits[$mode][$l]; - $words = (1 << $bits) - 1; - - if($mode == QR_MODE_KANJI) { - $words *= 2; // the number of bytes is required - } - - return $words; - } - - // Error correction code ----------------------------------------------- - // Table of the error correction code (Reed-Solomon block) - // See Table 12-16 (pp.30-36), JIS X0510:2004. - - public static $eccTable = array( - array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)), - array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1 - array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), - array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)), - array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)), - array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5 - array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)), - array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)), - array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)), - array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)), - array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10 - array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)), - array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)), - array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)), - array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)), - array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15 - array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)), - array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)), - array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)), - array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)), - array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20 - array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)), - array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)), - array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)), - array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)), - array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25 - array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), - array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)), - array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), - array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)), - array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 - array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)), - array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), - array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), - array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), - array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 - array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), - array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), - array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), - array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), - array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40 - ); - - //---------------------------------------------------------------------- - // CACHEABLE!!! - - public static function getEccSpec($version, $level, array &$spec) - { - if (count($spec) < 5) { - $spec = array(0,0,0,0,0); - } - - $b1 = self::$eccTable[$version][$level][0]; - $b2 = self::$eccTable[$version][$level][1]; - $data = self::getDataLength($version, $level); - $ecc = self::getECCLength($version, $level); - - if($b2 == 0) { - $spec[0] = $b1; - $spec[1] = (int)($data / $b1); - $spec[2] = (int)($ecc / $b1); - $spec[3] = 0; - $spec[4] = 0; - } else { - $spec[0] = $b1; - $spec[1] = (int)($data / ($b1 + $b2)); - $spec[2] = (int)($ecc / ($b1 + $b2)); - $spec[3] = $b2; - $spec[4] = $spec[1] + 1; - } - } - - // Alignment pattern --------------------------------------------------- - - // Positions of alignment patterns. - // This array includes only the second and the third position of the - // alignment patterns. Rest of them can be calculated from the distance - // between them. - - // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. - - public static $alignmentPattern = array( - array( 0, 0), - array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 - array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 - array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 - array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 - array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 - array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 - array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 - array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 - ); - - - /** -------------------------------------------------------------------- - * Put an alignment marker. - * @param frame - * @param width - * @param ox,oy center coordinate of the pattern - */ - public static function putAlignmentMarker(array &$frame, $ox, $oy) - { - $finder = array( - "\xa1\xa1\xa1\xa1\xa1", - "\xa1\xa0\xa0\xa0\xa1", - "\xa1\xa0\xa1\xa0\xa1", - "\xa1\xa0\xa0\xa0\xa1", - "\xa1\xa1\xa1\xa1\xa1" - ); - - $yStart = $oy-2; - $xStart = $ox-2; - - for($y=0; $y<5; $y++) { - QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]); - } - } - - //---------------------------------------------------------------------- - public static function putAlignmentPattern($version, &$frame, $width) - { - if($version < 2) - return; - - $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; - if($d < 0) { - $w = 2; - } else { - $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2); - } - if($w * $w - 3 == 1) { - $x = self::$alignmentPattern[$version][0]; - $y = self::$alignmentPattern[$version][0]; - self::putAlignmentMarker($frame, $x, $y); - return; - } + $yStart = $oy - 2; + $xStart = $ox - 2; + + for ($y = 0; $y < 5; $y++) { + QRstr::set($frame, $xStart, $yStart + $y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function putAlignmentPattern($version, &$frame, $width) + { + if ($version < 2) { + return; + } + + $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; + if ($d < 0) { + $w = 2; + } else { + $w = (int) (($width - self::$alignmentPattern[$version][0]) / $d + 2); + } + + if ($w * $w - 3 == 1) { + $x = self::$alignmentPattern[$version][0]; + $y = self::$alignmentPattern[$version][0]; + self::putAlignmentMarker($frame, $x, $y); + return; + } + $cx = self::$alignmentPattern[$version][0]; + for ($x = 1; $x < $w - 1; $x++) { + self::putAlignmentMarker($frame, 6, $cx); + self::putAlignmentMarker($frame, $cx, 6); + $cx += $d; + } + + $cy = self::$alignmentPattern[$version][0]; + for ($y = 0; $y < $w - 1; $y++) { $cx = self::$alignmentPattern[$version][0]; - for($x=1; $x<$w - 1; $x++) { - self::putAlignmentMarker($frame, 6, $cx); - self::putAlignmentMarker($frame, $cx, 6); + for ($x = 0; $x < $w - 1; $x++) { + self::putAlignmentMarker($frame, $cx, $cy); $cx += $d; } + $cy += $d; + } + } - $cy = self::$alignmentPattern[$version][0]; - for($y=0; $y<$w-1; $y++) { - $cx = self::$alignmentPattern[$version][0]; - for($x=0; $x<$w-1; $x++) { - self::putAlignmentMarker($frame, $cx, $cy); - $cx += $d; - } - $cy += $d; - } + // Version information pattern ----------------------------------------- + + // Version information pattern (BCH coded). + // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. + + // size: [QRSPEC_VERSION_MAX - 6] + + public static $versionPattern = array( + 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, + 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, + 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, + 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, + 0x27541, 0x28c69, + ); + + //---------------------------------------------------------------------- + public static function getVersionPattern($version) + { + if ($version < 7 || $version > QRSPEC_VERSION_MAX) { + return 0; } - // Version information pattern ----------------------------------------- + return self::$versionPattern[$version - 7]; + } + + // Format information -------------------------------------------------- + // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) - // Version information pattern (BCH coded). - // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. - - // size: [QRSPEC_VERSION_MAX - 6] - - public static $versionPattern = array( - 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, - 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, - 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, - 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, - 0x27541, 0x28c69 - ); + public static $formatInfo = array( + array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), + array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), + array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), + array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b), + ); - //---------------------------------------------------------------------- - public static function getVersionPattern($version) - { - if($version < 7 || $version > QRSPEC_VERSION_MAX) - return 0; + public static function getFormatInfo($mask, $level) + { + if ($mask < 0 || $mask > 7) { + return 0; + } - return self::$versionPattern[$version -7]; + if ($level < 0 || $level > 3) { + return 0; } - // Format information -------------------------------------------------- - // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) - - public static $formatInfo = array( - array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), - array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), - array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), - array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) + return self::$formatInfo[$level][$mask]; + } + + // Frame --------------------------------------------------------------- + // Cache of initial frames. + + public static $frames = array(); + + /** -------------------------------------------------------------------- + * Put a finder pattern. + * @param frame + * @param width + * @param ox,oy upper-left coordinate of the pattern + */ + public static function putFinderPattern(&$frame, $ox, $oy) + { + $finder = array( + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", ); - public static function getFormatInfo($mask, $level) - { - if($mask < 0 || $mask > 7) - return 0; - - if($level < 0 || $level > 3) - return 0; - - return self::$formatInfo[$level][$mask]; - } - - // Frame --------------------------------------------------------------- - // Cache of initial frames. - - public static $frames = array(); - - /** -------------------------------------------------------------------- - * Put a finder pattern. - * @param frame - * @param width - * @param ox,oy upper-left coordinate of the pattern - */ - public static function putFinderPattern(&$frame, $ox, $oy) - { - $finder = array( - "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", - "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", - "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", - "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", - "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", - "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", - "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" - ); - - for($y=0; $y<7; $y++) { - QRstr::set($frame, $ox, $oy+$y, $finder[$y]); - } - } - - //---------------------------------------------------------------------- - public static function createFrame($version) - { - $width = self::$capacity[$version][QRCAP_WIDTH]; - $frameLine = str_repeat ("\0", $width); - $frame = array_fill(0, $width, $frameLine); - - // Finder pattern - self::putFinderPattern($frame, 0, 0); - self::putFinderPattern($frame, $width - 7, 0); - self::putFinderPattern($frame, 0, $width - 7); - - // Separator - $yOffset = $width - 7; - - for($y=0; $y<7; $y++) { - $frame[$y][7] = "\xc0"; - $frame[$y][$width - 8] = "\xc0"; - $frame[$yOffset][7] = "\xc0"; - $yOffset++; - } - - $setPattern = str_repeat("\xc0", 8); - - QRstr::set($frame, 0, 7, $setPattern); - QRstr::set($frame, $width-8, 7, $setPattern); - QRstr::set($frame, 0, $width - 8, $setPattern); - - // Format info - $setPattern = str_repeat("\x84", 9); - QRstr::set($frame, 0, 8, $setPattern); - QRstr::set($frame, $width - 8, 8, $setPattern, 8); - - $yOffset = $width - 8; - - for($y=0; $y<8; $y++,$yOffset++) { - $frame[$y][8] = "\x84"; - $frame[$yOffset][8] = "\x84"; - } - - // Timing pattern - - for($i=1; $i<$width-15; $i++) { - $frame[6][7+$i] = chr(0x90 | ($i & 1)); - $frame[7+$i][6] = chr(0x90 | ($i & 1)); - } - - // Alignment pattern - self::putAlignmentPattern($version, $frame, $width); - - // Version information - if($version >= 7) { - $vinf = self::getVersionPattern($version); - - $v = $vinf; - - for($x=0; $x<6; $x++) { - for($y=0; $y<3; $y++) { - $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1)); - $v = $v >> 1; - } + for ($y = 0; $y < 7; $y++) { + QRstr::set($frame, $ox, $oy + $y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function createFrame($version) + { + $width = self::$capacity[$version][QRCAP_WIDTH]; + $frameLine = str_repeat("\0", $width); + $frame = array_fill(0, $width, $frameLine); + + // Finder pattern + self::putFinderPattern($frame, 0, 0); + self::putFinderPattern($frame, $width - 7, 0); + self::putFinderPattern($frame, 0, $width - 7); + + // Separator + $yOffset = $width - 7; + + for ($y = 0; $y < 7; $y++) { + $frame[$y][7] = "\xc0"; + $frame[$y][$width - 8] = "\xc0"; + $frame[$yOffset][7] = "\xc0"; + $yOffset++; + } + + $setPattern = str_repeat("\xc0", 8); + + QRstr::set($frame, 0, 7, $setPattern); + QRstr::set($frame, $width - 8, 7, $setPattern); + QRstr::set($frame, 0, $width - 8, $setPattern); + + // Format info + $setPattern = str_repeat("\x84", 9); + QRstr::set($frame, 0, 8, $setPattern); + QRstr::set($frame, $width - 8, 8, $setPattern, 8); + + $yOffset = $width - 8; + + for ($y = 0; $y < 8; $y++, $yOffset++) { + $frame[$y][8] = "\x84"; + $frame[$yOffset][8] = "\x84"; + } + + // Timing pattern + + for ($i = 1; $i < $width - 15; $i++) { + $frame[6][7 + $i] = chr(0x90 | ($i & 1)); + $frame[7 + $i][6] = chr(0x90 | ($i & 1)); + } + + // Alignment pattern + self::putAlignmentPattern($version, $frame, $width); + + // Version information + if ($version >= 7) { + $vinf = self::getVersionPattern($version); + + $v = $vinf; + + for ($x = 0; $x < 6; $x++) { + for ($y = 0; $y < 3; $y++) { + $frame[($width - 11) + $y][$x] = chr(0x88 | ($v & 1)); + $v = $v >> 1; } + } - $v = $vinf; - for($y=0; $y<6; $y++) { - for($x=0; $x<3; $x++) { - $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1)); - $v = $v >> 1; - } + $v = $vinf; + for ($y = 0; $y < 6; $y++) { + for ($x = 0; $x < 3; $x++) { + $frame[$y][$x + ($width - 11)] = chr(0x88 | ($v & 1)); + $v = $v >> 1; } } - - // and a little bit... - $frame[$width - 8][8] = "\x81"; - - return $frame; - } - - //---------------------------------------------------------------------- - public static function debug($frame, $binary_mode = false) - { - if ($binary_mode) { - - foreach ($frame as &$frameLine) { - $frameLine = join('  ', explode('0', $frameLine)); - $frameLine = join('██', explode('1', $frameLine)); - } - - ?> + } + + // and a little bit... + $frame[$width - 8][8] = "\x81"; + + return $frame; + } + + //---------------------------------------------------------------------- + public static function debug($frame, $binary_mode = false) + { + if ($binary_mode) { + + foreach ($frame as &$frameLine) { + $frameLine = join('  ', explode('0', $frameLine)); + $frameLine = join('██', explode('1', $frameLine)); + } + + ?>


        '; - echo join("
        ", $frame); - echo '






'; - - } else { - - foreach ($frame as &$frameLine) { - $frameLine = join(' ', explode("\xc0", $frameLine)); - $frameLine = join('', explode("\xc1", $frameLine)); - $frameLine = join(' ', explode("\xa0", $frameLine)); - $frameLine = join('', explode("\xa1", $frameLine)); - $frameLine = join('', explode("\x84", $frameLine)); //format 0 - $frameLine = join('', explode("\x85", $frameLine)); //format 1 - $frameLine = join('', explode("\x81", $frameLine)); //special bit - $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 - $frameLine = join('', explode("\x91", $frameLine)); //clock 1 - $frameLine = join(' ', explode("\x88", $frameLine)); //version - $frameLine = join('', explode("\x89", $frameLine)); //version - $frameLine = join('♦', explode("\x01", $frameLine)); - $frameLine = join('⋅', explode("\0", $frameLine)); - } - - ?> +echo '



        '; + echo join("
        ", $frame); + echo '






'; + + } else { + + foreach ($frame as &$frameLine) { + $frameLine = join(' ', explode("\xc0", $frameLine)); + $frameLine = join('', explode("\xc1", $frameLine)); + $frameLine = join(' ', explode("\xa0", $frameLine)); + $frameLine = join('', explode("\xa1", $frameLine)); + $frameLine = join('', explode("\x84", $frameLine)); //format 0 + $frameLine = join('', explode("\x85", $frameLine)); //format 1 + $frameLine = join('', explode("\x81", $frameLine)); //special bit + $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 + $frameLine = join('', explode("\x91", $frameLine)); //clock 1 + $frameLine = join(' ', explode("\x88", $frameLine)); //version + $frameLine = join('', explode("\x89", $frameLine)); //version + $frameLine = join('♦', explode("\x01", $frameLine)); + $frameLine = join('⋅', explode("\0", $frameLine)); + } + + ?> "; - echo join("
", $frame); - echo "
"; - - } - } +echo "
";
+            echo join("
", $frame); + echo "
"; - //---------------------------------------------------------------------- - public static function serial($frame) - { - return gzcompress(join("\n", $frame), 9); } - - //---------------------------------------------------------------------- - public static function unserial($code) - { - return explode("\n", gzuncompress($code)); + } + + //---------------------------------------------------------------------- + public static function serial($frame) + { + return gzcompress(join("\n", $frame), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + return explode("\n", gzuncompress($code)); + } + + //---------------------------------------------------------------------- + public static function newFrame($version) + { + if ($version < 1 || $version > QRSPEC_VERSION_MAX) { + return null; } - - //---------------------------------------------------------------------- - public static function newFrame($version) - { - if($version < 1 || $version > QRSPEC_VERSION_MAX) - return null; - if(!isset(self::$frames[$version])) { - - $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat'; - - if (QR_CACHEABLE) { - if (file_exists($fileName)) { - self::$frames[$version] = self::unserial(file_get_contents($fileName)); - } else { - self::$frames[$version] = self::createFrame($version); - file_put_contents($fileName, self::serial(self::$frames[$version])); - } + if (!isset(self::$frames[$version])) { + + $fileName = QR_CACHE_DIR . 'frame_' . $version . '.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + self::$frames[$version] = self::unserial(file_get_contents($fileName)); } else { self::$frames[$version] = self::createFrame($version); + file_put_contents($fileName, self::serial(self::$frames[$version])); } + } else { + self::$frames[$version] = self::createFrame($version); } - - if(is_null(self::$frames[$version])) - return null; + } - return self::$frames[$version]; + if (is_null(self::$frames[$version])) { + return null; } - //---------------------------------------------------------------------- - public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; } - public static function rsBlockNum1($spec) { return $spec[0]; } - public static function rsDataCodes1($spec) { return $spec[1]; } - public static function rsEccCodes1($spec) { return $spec[2]; } - public static function rsBlockNum2($spec) { return $spec[3]; } - public static function rsDataCodes2($spec) { return $spec[4]; } - public static function rsEccCodes2($spec) { return $spec[2]; } - public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); } - public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; } - + return self::$frames[$version]; } - + //---------------------------------------------------------------------- + public static function rsBlockNum($spec) + {return $spec[0] + $spec[3];} + public static function rsBlockNum1($spec) + {return $spec[0];} + public static function rsDataCodes1($spec) + {return $spec[1];} + public static function rsEccCodes1($spec) + {return $spec[2];} + public static function rsBlockNum2($spec) + {return $spec[3];} + public static function rsDataCodes2($spec) + {return $spec[4];} + public static function rsEccCodes2($spec) + {return $spec[2];} + public static function rsDataLength($spec) + {return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]);} + public static function rsEccLength($spec) + {return ($spec[0] + $spec[3]) * $spec[2];} + +} //---- qrimage.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -932,85 +930,81 @@ public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $s * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('QR_IMAGE', true); - - class QRimage { - - //---------------------------------------------------------------------- - public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) - { - $image = self::image($frame, $pixelPerPoint, $outerFrame); - - if ($filename === false) { - Header("Content-type: image/png"); + +define('QR_IMAGE', true); + +class QRimage +{ + + //---------------------------------------------------------------------- + public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4, $saveandprint = false) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/png"); + ImagePng($image); + } else { + if ($saveandprint === true) { + ImagePng($image, $filename); + header("Content-type: image/png"); ImagePng($image); } else { - if($saveandprint===TRUE){ - ImagePng($image, $filename); - header("Content-type: image/png"); - ImagePng($image); - }else{ - ImagePng($image, $filename); - } - } - - ImageDestroy($image); - } - - //---------------------------------------------------------------------- - public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) - { - $image = self::image($frame, $pixelPerPoint, $outerFrame); - - if ($filename === false) { - Header("Content-type: image/jpeg"); - ImageJpeg($image, null, $q); - } else { - ImageJpeg($image, $filename, $q); - } - - ImageDestroy($image); - } - - //---------------------------------------------------------------------- - private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) - { - $h = count($frame); - $w = strlen($frame[0]); - - $imgW = $w + 2*$outerFrame; - $imgH = $h + 2*$outerFrame; - - $base_image =ImageCreate($imgW, $imgH); - - $col[0] = ImageColorAllocate($base_image,255,255,255); - $col[1] = ImageColorAllocate($base_image,0,0,0); - - imagefill($base_image, 0, 0, $col[0]); - - for($y=0; $y<$h; $y++) { - for($x=0; $x<$w; $x++) { - if ($frame[$y][$x] == '1') { - ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]); - } - } + ImagePng($image, $filename); } - - $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); - ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); - ImageDestroy($base_image); - - return $target_image; } + + ImageDestroy($image); } + //---------------------------------------------------------------------- + public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/jpeg"); + ImageJpeg($image, null, $q); + } else { + ImageJpeg($image, $filename, $q); + } + + ImageDestroy($image); + } + //---------------------------------------------------------------------- + private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) + { + $h = count($frame); + $w = strlen($frame[0]); -//---- qrinput.php ----------------------------- + $imgW = $w + 2 * $outerFrame; + $imgH = $h + 2 * $outerFrame; + $base_image = ImageCreate($imgW, $imgH); + $col[0] = ImageColorAllocate($base_image, 255, 255, 255); + $col[1] = ImageColorAllocate($base_image, 0, 0, 0); + imagefill($base_image, 0, 0, $col[0]); + + for ($y = 0; $y < $h; $y++) { + for ($x = 0; $x < $w; $x++) { + if ($frame[$y][$x] == '1') { + ImageSetPixel($base_image, $x + $outerFrame, $y + $outerFrame, $col[1]); + } + } + } + + $target_image = ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); + ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); + ImageDestroy($base_image); + + return $target_image; + } +} + +//---- qrinput.php ----------------------------- /* * PHP QR Code encoder @@ -1037,716 +1031,739 @@ private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('STRUCTURE_HEADER_BITS', 20); - define('MAX_STRUCTURED_SYMBOLS', 16); - - class QRinputItem { - - public $mode; - public $size; - public $data; - public $bstream; - - public function __construct($mode, $size, $data, $bstream = null) - { - $setData = array_slice($data, 0, $size); - - if (count($setData) < $size) { - $setData = array_merge($setData, array_fill(0,$size-count($setData),0)); - } - - if(!QRinput::check($mode, $size, $setData)) { - throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData)); - return null; - } - - $this->mode = $mode; - $this->size = $size; - $this->data = $setData; - $this->bstream = $bstream; - } - - //---------------------------------------------------------------------- - public function encodeModeNum($version) - { - try { - - $words = (int)($this->size / 3); - $bs = new QRbitstream(); - - $val = 0x1; - $bs->appendNum(4, $val); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); - for($i=0; $i<$words; $i++) { - $val = (ord($this->data[$i*3 ]) - ord('0')) * 100; - $val += (ord($this->data[$i*3+1]) - ord('0')) * 10; - $val += (ord($this->data[$i*3+2]) - ord('0')); - $bs->appendNum(10, $val); - } +define('STRUCTURE_HEADER_BITS', 20); +define('MAX_STRUCTURED_SYMBOLS', 16); - if($this->size - $words * 3 == 1) { - $val = ord($this->data[$words*3]) - ord('0'); - $bs->appendNum(4, $val); - } else if($this->size - $words * 3 == 2) { - $val = (ord($this->data[$words*3 ]) - ord('0')) * 10; - $val += (ord($this->data[$words*3+1]) - ord('0')); - $bs->appendNum(7, $val); - } +class QRinputItem +{ - $this->bstream = $bs; - return 0; - - } catch (Exception $e) { - return -1; - } - } - - //---------------------------------------------------------------------- - public function encodeModeAn($version) - { - try { - $words = (int)($this->size / 2); - $bs = new QRbitstream(); - - $bs->appendNum(4, 0x02); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); + public $mode; + public $size; + public $data; + public $bstream; - for($i=0; $i<$words; $i++) { - $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45; - $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1])); + public function __construct($mode, $size, $data, $bstream = null) + { + $setData = array_slice($data, 0, $size); - $bs->appendNum(11, $val); - } + if (count($setData) < $size) { + $setData = array_merge($setData, array_fill(0, $size - count($setData), 0)); + } - if($this->size & 1) { - $val = QRinput::lookAnTable(ord($this->data[$words * 2])); - $bs->appendNum(6, $val); - } - - $this->bstream = $bs; - return 0; - - } catch (Exception $e) { - return -1; - } + if (!QRinput::check($mode, $size, $setData)) { + throw new Exception('Error m:' . $mode . ',s:' . $size . ',d:' . join(',', $setData)); + return null; } - - //---------------------------------------------------------------------- - public function encodeMode8($version) - { - try { - $bs = new QRbitstream(); - $bs->appendNum(4, 0x4); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); + $this->mode = $mode; + $this->size = $size; + $this->data = $setData; + $this->bstream = $bstream; + } - for($i=0; $i<$this->size; $i++) { - $bs->appendNum(8, ord($this->data[$i])); - } + //---------------------------------------------------------------------- + public function encodeModeNum($version) + { + try { - $this->bstream = $bs; - return 0; - - } catch (Exception $e) { - return -1; - } - } - - //---------------------------------------------------------------------- - public function encodeModeKanji($version) - { - try { + $words = (int) ($this->size / 3); + $bs = new QRbitstream(); - $bs = new QRbitrtream(); - - $bs->appendNum(4, 0x8); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2)); + $val = 0x1; + $bs->appendNum(4, $val); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); - for($i=0; $i<$this->size; $i+=2) { - $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]); - if($val <= 0x9ffc) { - $val -= 0x8140; - } else { - $val -= 0xc140; - } - - $h = ($val >> 8) * 0xc0; - $val = ($val & 0xff) + $h; + for ($i = 0; $i < $words; $i++) { + $val = (ord($this->data[$i * 3]) - ord('0')) * 100; + $val += (ord($this->data[$i * 3 + 1]) - ord('0')) * 10; + $val += (ord($this->data[$i * 3 + 2]) - ord('0')); + $bs->appendNum(10, $val); + } - $bs->appendNum(13, $val); - } + if ($this->size - $words * 3 == 1) { + $val = ord($this->data[$words * 3]) - ord('0'); + $bs->appendNum(4, $val); + } else if ($this->size - $words * 3 == 2) { + $val = (ord($this->data[$words * 3]) - ord('0')) * 10; + $val += (ord($this->data[$words * 3 + 1]) - ord('0')); + $bs->appendNum(7, $val); + } - $this->bstream = $bs; - return 0; - - } catch (Exception $e) { - return -1; + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeAn($version) + { + try { + $words = (int) ($this->size / 2); + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x02); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); + + for ($i = 0; $i < $words; $i++) { + $val = (int) QRinput::lookAnTable(ord($this->data[$i * 2])) * 45; + $val += (int) QRinput::lookAnTable(ord($this->data[$i * 2 + 1])); + + $bs->appendNum(11, $val); } + + if ($this->size & 1) { + $val = QRinput::lookAnTable(ord($this->data[$words * 2])); + $bs->appendNum(6, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; } + } - //---------------------------------------------------------------------- - public function encodeModeStructure() - { - try { - $bs = new QRbitstream(); - - $bs->appendNum(4, 0x03); - $bs->appendNum(4, ord($this->data[1]) - 1); - $bs->appendNum(4, ord($this->data[0]) - 1); - $bs->appendNum(8, ord($this->data[2])); + //---------------------------------------------------------------------- + public function encodeMode8($version) + { + try { + $bs = new QRbitstream(); - $this->bstream = $bs; - return 0; - - } catch (Exception $e) { - return -1; + $bs->appendNum(4, 0x4); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); + + for ($i = 0; $i < $this->size; $i++) { + $bs->appendNum(8, ord($this->data[$i])); } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; } - - //---------------------------------------------------------------------- - public function estimateBitStreamSizeOfEntry($version) - { - $bits = 0; - - if($version == 0) - $version = 1; - - switch($this->mode) { - case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break; - case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break; - case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break; - case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break; - case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; - default: - return 0; - } - - $l = QRspec::lengthIndicator($this->mode, $version); - $m = 1 << $l; - $num = (int)(($this->size + $m - 1) / $m); - - $bits += $num * (4 + $l); - - return $bits; - } - - //---------------------------------------------------------------------- - public function encodeBitStream($version) - { - try { - - unset($this->bstream); - $words = QRspec::maximumWords($this->mode, $version); - - if($this->size > $words) { - - $st1 = new QRinputItem($this->mode, $words, $this->data); - $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); - - $st1->encodeBitStream($version); - $st2->encodeBitStream($version); - - $this->bstream = new QRbitstream(); - $this->bstream->append($st1->bstream); - $this->bstream->append($st2->bstream); - - unset($st1); - unset($st2); - + } + + //---------------------------------------------------------------------- + public function encodeModeKanji($version) + { + try { + + $bs = new QRbitrtream(); + + $bs->appendNum(4, 0x8); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int) ($this->size / 2)); + + for ($i = 0; $i < $this->size; $i += 2) { + $val = (ord($this->data[$i]) << 8) | ord($this->data[$i + 1]); + if ($val <= 0x9ffc) { + $val -= 0x8140; } else { - - $ret = 0; - - switch($this->mode) { - case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break; - case QR_MODE_AN: $ret = $this->encodeModeAn($version); break; - case QR_MODE_8: $ret = $this->encodeMode8($version); break; - case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break; - case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break; - - default: - break; - } - - if($ret < 0) - return -1; + $val -= 0xc140; } - return $this->bstream->size(); - - } catch (Exception $e) { - return -1; - } - } - }; - - //########################################################################## - - class QRinput { - - public $items; - - private $version; - private $level; - - //---------------------------------------------------------------------- - public function __construct($version = 0, $level = QR_ECLEVEL_L) - { - if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { - throw new Exception('Invalid version no'); - return NULL; - } - - $this->version = $version; - $this->level = $level; - } - - //---------------------------------------------------------------------- - public function getVersion() - { - return $this->version; - } - - //---------------------------------------------------------------------- - public function setVersion($version) - { - if($version < 0 || $version > QRSPEC_VERSION_MAX) { - throw new Exception('Invalid version no'); - return -1; - } + $h = ($val >> 8) * 0xc0; + $val = ($val & 0xff) + $h; - $this->version = $version; + $bs->appendNum(13, $val); + } + $this->bstream = $bs; return 0; + + } catch (Exception $e) { + return -1; } - - //---------------------------------------------------------------------- - public function getErrorCorrectionLevel() - { - return $this->level; - } + } - //---------------------------------------------------------------------- - public function setErrorCorrectionLevel($level) - { - if($level > QR_ECLEVEL_H) { - throw new Exception('Invalid ECLEVEL'); - return -1; - } + //---------------------------------------------------------------------- + public function encodeModeStructure() + { + try { + $bs = new QRbitstream(); - $this->level = $level; + $bs->appendNum(4, 0x03); + $bs->appendNum(4, ord($this->data[1]) - 1); + $bs->appendNum(4, ord($this->data[0]) - 1); + $bs->appendNum(8, ord($this->data[2])); + $this->bstream = $bs; return 0; + + } catch (Exception $e) { + return -1; } - - //---------------------------------------------------------------------- - public function appendEntry(QRinputItem $entry) - { - $this->items[] = $entry; - } - - //---------------------------------------------------------------------- - public function append($mode, $size, $data) - { - try { - $entry = new QRinputItem($mode, $size, $data); - $this->items[] = $entry; - return 0; - } catch (Exception $e) { - return -1; - } - } - - //---------------------------------------------------------------------- - - public function insertStructuredAppendHeader($size, $index, $parity) - { - if( $size > MAX_STRUCTURED_SYMBOLS ) { - throw new Exception('insertStructuredAppendHeader wrong size'); - } - - if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) { - throw new Exception('insertStructuredAppendHeader wrong index'); - } + } - $buf = array($size, $index, $parity); - - try { - $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); - array_unshift($this->items, $entry); + //---------------------------------------------------------------------- + public function estimateBitStreamSizeOfEntry($version) + { + $bits = 0; + + if ($version == 0) { + $version = 1; + } + + switch ($this->mode) { + case QR_MODE_NUM:$bits = QRinput::estimateBitsModeNum($this->size); + break; + case QR_MODE_AN:$bits = QRinput::estimateBitsModeAn($this->size); + break; + case QR_MODE_8:$bits = QRinput::estimateBitsMode8($this->size); + break; + case QR_MODE_KANJI:$bits = QRinput::estimateBitsModeKanji($this->size); + break; + case QR_MODE_STRUCTURE:return STRUCTURE_HEADER_BITS; + default: return 0; - } catch (Exception $e) { - return -1; - } } - //---------------------------------------------------------------------- - public function calcParity() - { - $parity = 0; - - foreach($this->items as $item) { - if($item->mode != QR_MODE_STRUCTURE) { - for($i=$item->size-1; $i>=0; $i--) { - $parity ^= $item->data[$i]; - } + $l = QRspec::lengthIndicator($this->mode, $version); + $m = 1 << $l; + $num = (int) (($this->size + $m - 1) / $m); + + $bits += $num * (4 + $l); + + return $bits; + } + + //---------------------------------------------------------------------- + public function encodeBitStream($version) + { + try { + + unset($this->bstream); + $words = QRspec::maximumWords($this->mode, $version); + + if ($this->size > $words) { + + $st1 = new QRinputItem($this->mode, $words, $this->data); + $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); + + $st1->encodeBitStream($version); + $st2->encodeBitStream($version); + + $this->bstream = new QRbitstream(); + $this->bstream->append($st1->bstream); + $this->bstream->append($st2->bstream); + + unset($st1); + unset($st2); + + } else { + + $ret = 0; + + switch ($this->mode) { + case QR_MODE_NUM:$ret = $this->encodeModeNum($version); + break; + case QR_MODE_AN:$ret = $this->encodeModeAn($version); + break; + case QR_MODE_8:$ret = $this->encodeMode8($version); + break; + case QR_MODE_KANJI:$ret = $this->encodeModeKanji($version); + break; + case QR_MODE_STRUCTURE:$ret = $this->encodeModeStructure(); + break; + + default: + break; } - } - return $parity; - } - - //---------------------------------------------------------------------- - public static function checkModeNum($size, $data) - { - for($i=0; $i<$size; $i++) { - if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){ - return false; + if ($ret < 0) { + return -1; } + } - return true; + return $this->bstream->size(); + + } catch (Exception $e) { + return -1; } + } +}; - //---------------------------------------------------------------------- - public static function estimateBitsModeNum($size) - { - $w = (int)$size / 3; - $bits = $w * 10; - - switch($size - $w * 3) { - case 1: - $bits += 4; - break; - case 2: - $bits += 7; - break; - default: - break; - } +//########################################################################## - return $bits; +class QRinput +{ + + public $items; + + private $version; + private $level; + + //---------------------------------------------------------------------- + public function __construct($version = 0, $level = QR_ECLEVEL_L) + { + if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { + throw new Exception('Invalid version no'); + return null; } - - //---------------------------------------------------------------------- - public static $anTable = array( - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, - -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - ); - - //---------------------------------------------------------------------- - public static function lookAnTable($c) - { - return (($c > 127)?-1:self::$anTable[$c]); - } - - //---------------------------------------------------------------------- - public static function checkModeAn($size, $data) - { - for($i=0; $i<$size; $i++) { - if (self::lookAnTable(ord($data[$i])) == -1) { - return false; - } - } - return true; + $this->version = $version; + $this->level = $level; + } + + //---------------------------------------------------------------------- + public function getVersion() + { + return $this->version; + } + + //---------------------------------------------------------------------- + public function setVersion($version) + { + if ($version < 0 || $version > QRSPEC_VERSION_MAX) { + throw new Exception('Invalid version no'); + return -1; } - - //---------------------------------------------------------------------- - public static function estimateBitsModeAn($size) - { - $w = (int)($size / 2); - $bits = $w * 11; - - if($size & 1) { - $bits += 6; - } - return $bits; + $this->version = $version; + + return 0; + } + + //---------------------------------------------------------------------- + public function getErrorCorrectionLevel() + { + return $this->level; + } + + //---------------------------------------------------------------------- + public function setErrorCorrectionLevel($level) + { + if ($level > QR_ECLEVEL_H) { + throw new Exception('Invalid ECLEVEL'); + return -1; } - - //---------------------------------------------------------------------- - public static function estimateBitsMode8($size) - { - return $size * 8; + + $this->level = $level; + + return 0; + } + + //---------------------------------------------------------------------- + public function appendEntry(QRinputItem $entry) + { + $this->items[] = $entry; + } + + //---------------------------------------------------------------------- + public function append($mode, $size, $data) + { + try { + $entry = new QRinputItem($mode, $size, $data); + $this->items[] = $entry; + return 0; + } catch (Exception $e) { + return -1; } - - //---------------------------------------------------------------------- - public function estimateBitsModeKanji($size) - { - return (int)(($size / 2) * 13); + } + + //---------------------------------------------------------------------- + + public function insertStructuredAppendHeader($size, $index, $parity) + { + if ($size > MAX_STRUCTURED_SYMBOLS) { + throw new Exception('insertStructuredAppendHeader wrong size'); } - - //---------------------------------------------------------------------- - public static function checkModeKanji($size, $data) - { - if($size & 1) - return false; - for($i=0; $i<$size; $i+=2) { - $val = (ord($data[$i]) << 8) | ord($data[$i+1]); - if( $val < 0x8140 - || ($val > 0x9ffc && $val < 0xe040) - || $val > 0xebbf) { - return false; + if ($index <= 0 || $index > MAX_STRUCTURED_SYMBOLS) { + throw new Exception('insertStructuredAppendHeader wrong index'); + } + + $buf = array($size, $index, $parity); + + try { + $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); + array_unshift($this->items, $entry); + return 0; + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function calcParity() + { + $parity = 0; + + foreach ($this->items as $item) { + if ($item->mode != QR_MODE_STRUCTURE) { + for ($i = $item->size - 1; $i >= 0; $i--) { + $parity ^= $item->data[$i]; } } - - return true; } - /*********************************************************************** - * Validation - **********************************************************************/ + return $parity; + } - public static function check($mode, $size, $data) - { - if($size <= 0) + //---------------------------------------------------------------------- + public static function checkModeNum($size, $data) + { + for ($i = 0; $i < $size; $i++) { + if ((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))) { return false; + } + } - switch($mode) { - case QR_MODE_NUM: return self::checkModeNum($size, $data); break; - case QR_MODE_AN: return self::checkModeAn($size, $data); break; - case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break; - case QR_MODE_8: return true; break; - case QR_MODE_STRUCTURE: return true; break; - - default: - break; + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeNum($size) + { + $w = (int) $size / 3; + $bits = $w * 10; + + switch ($size - $w * 3) { + case 1: + $bits += 4; + break; + case 2: + $bits += 7; + break; + default: + break; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static $anTable = array( + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + ); + + //---------------------------------------------------------------------- + public static function lookAnTable($c) + { + return (($c > 127) ? -1 : self::$anTable[$c]); + } + + //---------------------------------------------------------------------- + public static function checkModeAn($size, $data) + { + for ($i = 0; $i < $size; $i++) { + if (self::lookAnTable(ord($data[$i])) == -1) { + return false; } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeAn($size) + { + $w = (int) ($size / 2); + $bits = $w * 11; + + if ($size & 1) { + $bits += 6; + } + return $bits; + } + + //---------------------------------------------------------------------- + public static function estimateBitsMode8($size) + { + return $size * 8; + } + + //---------------------------------------------------------------------- + public function estimateBitsModeKanji($size) + { + return (int) (($size / 2) * 13); + } + + //---------------------------------------------------------------------- + public static function checkModeKanji($size, $data) + { + if ($size & 1) { return false; } - - - //---------------------------------------------------------------------- - public function estimateBitStreamSize($version) - { - $bits = 0; - - foreach($this->items as $item) { - $bits += $item->estimateBitStreamSizeOfEntry($version); - } - - return $bits; - } - - //---------------------------------------------------------------------- - public function estimateVersion() - { - $version = 0; - $prev = 0; - do { - $prev = $version; - $bits = $this->estimateBitStreamSize($prev); - $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); - if ($version < 0) { - return -1; - } - } while ($version > $prev); - - return $version; - } - - //---------------------------------------------------------------------- - public static function lengthOfCode($mode, $version, $bits) - { - $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); - switch($mode) { - case QR_MODE_NUM: - $chunks = (int)($payload / 10); - $remain = $payload - $chunks * 10; - $size = $chunks * 3; - if($remain >= 7) { - $size += 2; - } else if($remain >= 4) { - $size += 1; - } - break; - case QR_MODE_AN: - $chunks = (int)($payload / 11); - $remain = $payload - $chunks * 11; - $size = $chunks * 2; - if($remain >= 6) - $size++; - break; - case QR_MODE_8: - $size = (int)($payload / 8); - break; - case QR_MODE_KANJI: - $size = (int)(($payload / 13) * 2); - break; - case QR_MODE_STRUCTURE: - $size = (int)($payload / 8); - break; - default: - $size = 0; - break; + + for ($i = 0; $i < $size; $i += 2) { + $val = (ord($data[$i]) << 8) | ord($data[$i + 1]); + if ($val < 0x8140 + || ($val > 0x9ffc && $val < 0xe040) + || $val > 0xebbf) { + return false; } - - $maxsize = QRspec::maximumWords($mode, $version); - if($size < 0) $size = 0; - if($size > $maxsize) $size = $maxsize; + } - return $size; + return true; + } + + /*********************************************************************** + * Validation + **********************************************************************/ + + public static function check($mode, $size, $data) + { + if ($size <= 0) { + return false; } - - //---------------------------------------------------------------------- - public function createBitStream() - { - $total = 0; - foreach($this->items as $item) { - $bits = $item->encodeBitStream($this->version); - - if($bits < 0) - return -1; - - $total += $bits; - } + switch ($mode) { + case QR_MODE_NUM:return self::checkModeNum($size, $data); + break; + case QR_MODE_AN:return self::checkModeAn($size, $data); + break; + case QR_MODE_KANJI:return self::checkModeKanji($size, $data); + break; + case QR_MODE_8:return true; + break; + case QR_MODE_STRUCTURE:return true; + break; - return $total; + default: + break; } - - //---------------------------------------------------------------------- - public function convertData() - { - $ver = $this->estimateVersion(); - if($ver > $this->getVersion()) { - $this->setVersion($ver); + + return false; + } + + //---------------------------------------------------------------------- + public function estimateBitStreamSize($version) + { + $bits = 0; + + foreach ($this->items as $item) { + $bits += $item->estimateBitStreamSizeOfEntry($version); + } + + return $bits; + } + + //---------------------------------------------------------------------- + public function estimateVersion() + { + $version = 0; + $prev = 0; + do { + $prev = $version; + $bits = $this->estimateBitStreamSize($prev); + $version = QRspec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); + if ($version < 0) { + return -1; } + } while ($version > $prev); - for(;;) { - $bits = $this->createBitStream(); - - if($bits < 0) - return -1; - - $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); - if($ver < 0) { - throw new Exception('WRONG VERSION'); - return -1; - } else if($ver > $this->getVersion()) { - $this->setVersion($ver); - } else { - break; + return $version; + } + + //---------------------------------------------------------------------- + public static function lengthOfCode($mode, $version, $bits) + { + $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); + switch ($mode) { + case QR_MODE_NUM: + $chunks = (int) ($payload / 10); + $remain = $payload - $chunks * 10; + $size = $chunks * 3; + if ($remain >= 7) { + $size += 2; + } else if ($remain >= 4) { + $size += 1; + } + break; + case QR_MODE_AN: + $chunks = (int) ($payload / 11); + $remain = $payload - $chunks * 11; + $size = $chunks * 2; + if ($remain >= 6) { + $size++; } + + break; + case QR_MODE_8: + $size = (int) ($payload / 8); + break; + case QR_MODE_KANJI: + $size = (int) (($payload / 13) * 2); + break; + case QR_MODE_STRUCTURE: + $size = (int) ($payload / 8); + break; + default: + $size = 0; + break; + } + + $maxsize = QRspec::maximumWords($mode, $version); + if ($size < 0) { + $size = 0; + } + + if ($size > $maxsize) { + $size = $maxsize; + } + + return $size; + } + + //---------------------------------------------------------------------- + public function createBitStream() + { + $total = 0; + + foreach ($this->items as $item) { + $bits = $item->encodeBitStream($this->version); + + if ($bits < 0) { + return -1; } - return 0; + $total += $bits; } - - //---------------------------------------------------------------------- - public function appendPaddingBit(&$bstream) - { - $bits = $bstream->size(); - $maxwords = QRspec::getDataLength($this->version, $this->level); - $maxbits = $maxwords * 8; - if ($maxbits == $bits) { - return 0; + return $total; + } + + //---------------------------------------------------------------------- + public function convertData() + { + $ver = $this->estimateVersion(); + if ($ver > $this->getVersion()) { + $this->setVersion($ver); + } + + for (;;) { + $bits = $this->createBitStream(); + + if ($bits < 0) { + return -1; } - if ($maxbits - $bits < 5) { - return $bstream->appendNum($maxbits - $bits, 0); + $ver = QRspec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); + if ($ver < 0) { + throw new Exception('WRONG VERSION'); + return -1; + } else if ($ver > $this->getVersion()) { + $this->setVersion($ver); + } else { + break; } + } - $bits += 4; - $words = (int)(($bits + 7) / 8); + return 0; + } - $padding = new QRbitstream(); - $ret = $padding->appendNum($words * 8 - $bits + 4, 0); - - if($ret < 0) - return $ret; + //---------------------------------------------------------------------- + public function appendPaddingBit(&$bstream) + { + $bits = $bstream->size(); + $maxwords = QRspec::getDataLength($this->version, $this->level); + $maxbits = $maxwords * 8; - $padlen = $maxwords - $words; - - if($padlen > 0) { - - $padbuf = array(); - for($i=0; $i<$padlen; $i++) { - $padbuf[$i] = ($i&1)?0x11:0xec; - } - - $ret = $padding->appendBytes($padlen, $padbuf); - - if($ret < 0) - return $ret; - - } + if ($maxbits == $bits) { + return 0; + } + + if ($maxbits - $bits < 5) { + return $bstream->appendNum($maxbits - $bits, 0); + } + + $bits += 4; + $words = (int) (($bits + 7) / 8); - $ret = $bstream->append($padding); - + $padding = new QRbitstream(); + $ret = $padding->appendNum($words * 8 - $bits + 4, 0); + + if ($ret < 0) { return $ret; } - //---------------------------------------------------------------------- - public function mergeBitStream() - { - if($this->convertData() < 0) { - return null; + $padlen = $maxwords - $words; + + if ($padlen > 0) { + + $padbuf = array(); + for ($i = 0; $i < $padlen; $i++) { + $padbuf[$i] = ($i & 1) ? 0x11 : 0xec; } - $bstream = new QRbitstream(); - - foreach($this->items as $item) { - $ret = $bstream->append($item->bstream); - if($ret < 0) { - return null; - } + $ret = $padding->appendBytes($padlen, $padbuf); + + if ($ret < 0) { + return $ret; } - return $bstream; } - //---------------------------------------------------------------------- - public function getBitStream() - { + $ret = $bstream->append($padding); - $bstream = $this->mergeBitStream(); - - if($bstream == null) { - return null; - } - - $ret = $this->appendPaddingBit($bstream); - if($ret < 0) { - return null; - } + return $ret; + } - return $bstream; + //---------------------------------------------------------------------- + public function mergeBitStream() + { + if ($this->convertData() < 0) { + return null; } - - //---------------------------------------------------------------------- - public function getByteStream() - { - $bstream = $this->getBitStream(); - if($bstream == null) { + + $bstream = new QRbitstream(); + + foreach ($this->items as $item) { + $ret = $bstream->append($item->bstream); + if ($ret < 0) { return null; } - - return $bstream->toByte(); } + + return $bstream; } - - - + //---------------------------------------------------------------------- + public function getBitStream() + { + $bstream = $this->mergeBitStream(); -//---- qrbitstream.php ----------------------------- + if ($bstream == null) { + return null; + } + $ret = $this->appendPaddingBit($bstream); + if ($ret < 0) { + return null; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getByteStream() + { + $bstream = $this->getBitStream(); + if ($bstream == null) { + return null; + } + return $bstream->toByte(); + } +} +//---- qrbitstream.php ----------------------------- /* * PHP QR Code encoder @@ -1773,168 +1790,167 @@ public function getByteStream() * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRbitstream { - - public $data = array(); - - //---------------------------------------------------------------------- - public function size() - { - return count($this->data); - } - - //---------------------------------------------------------------------- - public function allocate($setLength) - { - $this->data = array_fill(0, $setLength, 0); - return 0; + +class QRbitstream +{ + + public $data = array(); + + //---------------------------------------------------------------------- + public function size() + { + return count($this->data); + } + + //---------------------------------------------------------------------- + public function allocate($setLength) + { + $this->data = array_fill(0, $setLength, 0); + return 0; + } + + //---------------------------------------------------------------------- + public static function newFromNum($bits, $num) + { + $bstream = new QRbitstream(); + $bstream->allocate($bits); + + $mask = 1 << ($bits - 1); + for ($i = 0; $i < $bits; $i++) { + if ($num & $mask) { + $bstream->data[$i] = 1; + } else { + $bstream->data[$i] = 0; + } + $mask = $mask >> 1; } - - //---------------------------------------------------------------------- - public static function newFromNum($bits, $num) - { - $bstream = new QRbitstream(); - $bstream->allocate($bits); - - $mask = 1 << ($bits - 1); - for($i=0; $i<$bits; $i++) { - if($num & $mask) { - $bstream->data[$i] = 1; + + return $bstream; + } + + //---------------------------------------------------------------------- + public static function newFromBytes($size, $data) + { + $bstream = new QRbitstream(); + $bstream->allocate($size * 8); + $p = 0; + + for ($i = 0; $i < $size; $i++) { + $mask = 0x80; + for ($j = 0; $j < 8; $j++) { + if ($data[$i] & $mask) { + $bstream->data[$p] = 1; } else { - $bstream->data[$i] = 0; + $bstream->data[$p] = 0; } + $p++; $mask = $mask >> 1; } - - return $bstream; } - - //---------------------------------------------------------------------- - public static function newFromBytes($size, $data) - { - $bstream = new QRbitstream(); - $bstream->allocate($size * 8); - $p=0; - for($i=0; $i<$size; $i++) { - $mask = 0x80; - for($j=0; $j<8; $j++) { - if($data[$i] & $mask) { - $bstream->data[$p] = 1; - } else { - $bstream->data[$p] = 0; - } - $p++; - $mask = $mask >> 1; - } - } + return $bstream; + } - return $bstream; + //---------------------------------------------------------------------- + public function append(QRbitstream $arg) + { + if (is_null($arg)) { + return -1; } - - //---------------------------------------------------------------------- - public function append(QRbitstream $arg) - { - if (is_null($arg)) { - return -1; - } - - if($arg->size() == 0) { - return 0; - } - - if($this->size() == 0) { - $this->data = $arg->data; - return 0; - } - - $this->data = array_values(array_merge($this->data, $arg->data)); + if ($arg->size() == 0) { return 0; } - - //---------------------------------------------------------------------- - public function appendNum($bits, $num) - { - if ($bits == 0) - return 0; - $b = QRbitstream::newFromNum($bits, $num); - - if(is_null($b)) - return -1; + if ($this->size() == 0) { + $this->data = $arg->data; + return 0; + } - $ret = $this->append($b); - unset($b); + $this->data = array_values(array_merge($this->data, $arg->data)); - return $ret; + return 0; + } + + //---------------------------------------------------------------------- + public function appendNum($bits, $num) + { + if ($bits == 0) { + return 0; } - //---------------------------------------------------------------------- - public function appendBytes($size, $data) - { - if ($size == 0) - return 0; + $b = QRbitstream::newFromNum($bits, $num); - $b = QRbitstream::newFromBytes($size, $data); - - if(is_null($b)) - return -1; + if (is_null($b)) { + return -1; + } - $ret = $this->append($b); - unset($b); + $ret = $this->append($b); + unset($b); - return $ret; + return $ret; + } + + //---------------------------------------------------------------------- + public function appendBytes($size, $data) + { + if ($size == 0) { + return 0; } - - //---------------------------------------------------------------------- - public function toByte() - { - - $size = $this->size(); - - if($size == 0) { - return array(); - } - - $data = array_fill(0, (int)(($size + 7) / 8), 0); - $bytes = (int)($size / 8); - - $p = 0; - - for($i=0; $i<$bytes; $i++) { - $v = 0; - for($j=0; $j<8; $j++) { - $v = $v << 1; - $v |= $this->data[$p]; - $p++; - } - $data[$i] = $v; - } - - if($size & 7) { - $v = 0; - for($j=0; $j<($size & 7); $j++) { - $v = $v << 1; - $v |= $this->data[$p]; - $p++; - } - $data[$bytes] = $v; - } - return $data; + $b = QRbitstream::newFromBytes($size, $data); + + if (is_null($b)) { + return -1; } + $ret = $this->append($b); + unset($b); + + return $ret; } + //---------------------------------------------------------------------- + public function toByte() + { + $size = $this->size(); + if ($size == 0) { + return array(); + } -//---- qrsplit.php ----------------------------- + $data = array_fill(0, (int) (($size + 7) / 8), 0); + $bytes = (int) ($size / 8); + + $p = 0; + + for ($i = 0; $i < $bytes; $i++) { + $v = 0; + for ($j = 0; $j < 8; $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$i] = $v; + } + + if ($size & 7) { + $v = 0; + for ($j = 0; $j < ($size & 7); $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$bytes] = $v; + } + return $data; + } +} +//---- qrsplit.php ----------------------------- /* * PHP QR Code encoder @@ -1950,7 +1966,7 @@ public function toByte() * The following data / specifications are taken from * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) * or - * "Automatic identification and data capture techniques -- + * "Automatic identification and data capture techniques -- * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) * * This library is free software; you can redistribute it and/or @@ -1967,298 +1983,312 @@ public function toByte() * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - class QRsplit { - - public $dataStr = ''; - public $input; - public $modeHint; - - //---------------------------------------------------------------------- - public function __construct($dataStr, $input, $modeHint) - { - $this->dataStr = $dataStr; - $this->input = $input; - $this->modeHint = $modeHint; - } - - //---------------------------------------------------------------------- - public static function isdigitat($str, $pos) - { - if ($pos >= strlen($str)) - return false; - - return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9'))); - } - - //---------------------------------------------------------------------- - public static function isalnumat($str, $pos) - { - if ($pos >= strlen($str)) - return false; - - return (QRinput::lookAnTable(ord($str[$pos])) >= 0); - } - - //---------------------------------------------------------------------- - public function identifyMode($pos) - { - if ($pos >= strlen($this->dataStr)) - return QR_MODE_NUL; - - $c = $this->dataStr[$pos]; - - if(self::isdigitat($this->dataStr, $pos)) { - return QR_MODE_NUM; - } else if(self::isalnumat($this->dataStr, $pos)) { - return QR_MODE_AN; - } else if($this->modeHint == QR_MODE_KANJI) { - - if ($pos+1 < strlen($this->dataStr)) - { - $d = $this->dataStr[$pos+1]; - $word = (ord($c) << 8) | ord($d); - if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { - return QR_MODE_KANJI; - } +class QRsplit +{ + + public $dataStr = ''; + public $input; + public $modeHint; + + //---------------------------------------------------------------------- + public function __construct($dataStr, $input, $modeHint) + { + $this->dataStr = $dataStr; + $this->input = $input; + $this->modeHint = $modeHint; + } + + //---------------------------------------------------------------------- + public static function isdigitat($str, $pos) + { + if ($pos >= strlen($str)) { + return false; + } + + return ((ord($str[$pos]) >= ord('0')) && (ord($str[$pos]) <= ord('9'))); + } + + //---------------------------------------------------------------------- + public static function isalnumat($str, $pos) + { + if ($pos >= strlen($str)) { + return false; + } + + return (QRinput::lookAnTable(ord($str[$pos])) >= 0); + } + + //---------------------------------------------------------------------- + public function identifyMode($pos) + { + if ($pos >= strlen($this->dataStr)) { + return QR_MODE_NUL; + } + + $c = $this->dataStr[$pos]; + + if (self::isdigitat($this->dataStr, $pos)) { + return QR_MODE_NUM; + } else if (self::isalnumat($this->dataStr, $pos)) { + return QR_MODE_AN; + } else if ($this->modeHint == QR_MODE_KANJI) { + + if ($pos + 1 < strlen($this->dataStr)) { + $d = $this->dataStr[$pos + 1]; + $word = (ord($c) << 8) | ord($d); + if (($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { + return QR_MODE_KANJI; } } + } - return QR_MODE_8; - } - - //---------------------------------------------------------------------- - public function eatNum() - { - $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + return QR_MODE_8; + } - $p = 0; - while(self::isdigitat($this->dataStr, $p)) { - $p++; + //---------------------------------------------------------------------- + public function eatNum() + { + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + while (self::isdigitat($this->dataStr, $p)) { + $p++; + } + + $run = $p; + $mode = $this->identifyMode($p); + + if ($mode == QR_MODE_8) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if ($dif > 0) { + return $this->eat8(); } - - $run = $p; - $mode = $this->identifyMode($p); - - if($mode == QR_MODE_8) { - $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln - + QRinput::estimateBitsMode8(1) // + 4 + l8 - - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 - if($dif > 0) { - return $this->eat8(); - } + } + if ($mode == QR_MODE_AN) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsModeAn(1) // + 4 + la + - QRinput::estimateBitsModeAn($run + 1); // - 4 - la + if ($dif > 0) { + return $this->eatAn(); } - if($mode == QR_MODE_AN) { - $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln - + QRinput::estimateBitsModeAn(1) // + 4 + la - - QRinput::estimateBitsModeAn($run + 1);// - 4 - la - if($dif > 0) { - return $this->eatAn(); + } + + $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); + if ($ret < 0) { + return -1; + } + + return $run; + } + + //---------------------------------------------------------------------- + public function eatAn() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + + while (self::isalnumat($this->dataStr, $p)) { + if (self::isdigitat($this->dataStr, $p)) { + $q = $p; + while (self::isdigitat($this->dataStr, $q)) { + $q++; } - } - - $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); - if($ret < 0) - return -1; - return $run; - } - - //---------------------------------------------------------------------- - public function eatAn() - { - $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); - $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); - - $p = 0; - - while(self::isalnumat($this->dataStr, $p)) { - if(self::isdigitat($this->dataStr, $p)) { - $q = $p; - while(self::isdigitat($this->dataStr, $q)) { - $q++; - } - - $dif = QRinput::estimateBitsModeAn($p) // + 4 + la - + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln - - QRinput::estimateBitsModeAn($q); // - 4 - la - - if($dif < 0) { - break; - } else { - $p = $q; - } + $dif = QRinput::estimateBitsModeAn($p) // + 4 + la + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsModeAn($q); // - 4 - la + + if ($dif < 0) { + break; } else { - $p++; + $p = $q; } + } else { + $p++; } + } - $run = $p; + $run = $p; - if(!self::isalnumat($this->dataStr, $p)) { - $dif = QRinput::estimateBitsModeAn($run) + 4 + $la - + QRinput::estimateBitsMode8(1) // + 4 + l8 - - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 - if($dif > 0) { - return $this->eat8(); - } + if (!self::isalnumat($this->dataStr, $p)) { + $dif = QRinput::estimateBitsModeAn($run) + 4 + $la + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if ($dif > 0) { + return $this->eat8(); } + } - $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); - if($ret < 0) - return -1; + $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); + if ($ret < 0) { + return -1; + } - return $run; + return $run; + } + + //---------------------------------------------------------------------- + public function eatKanji() + { + $p = 0; + + while ($this->identifyMode($p) == QR_MODE_KANJI) { + $p += 2; } - - //---------------------------------------------------------------------- - public function eatKanji() - { - $p = 0; - - while($this->identifyMode($p) == QR_MODE_KANJI) { - $p += 2; - } - - $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); - if($ret < 0) - return -1; - return $run; + $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); + if ($ret < 0) { + return -1; } - //---------------------------------------------------------------------- - public function eat8() - { - $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); - $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + return $run; + } + + //---------------------------------------------------------------------- + public function eat8() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 1; + $dataStrLen = strlen($this->dataStr); - $p = 1; - $dataStrLen = strlen($this->dataStr); - - while($p < $dataStrLen) { - - $mode = $this->identifyMode($p); - if($mode == QR_MODE_KANJI) { + while ($p < $dataStrLen) { + + $mode = $this->identifyMode($p); + if ($mode == QR_MODE_KANJI) { + break; + } + if ($mode == QR_MODE_NUM) { + $q = $p; + while (self::isdigitat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if ($dif < 0) { break; + } else { + $p = $q; } - if($mode == QR_MODE_NUM) { - $q = $p; - while(self::isdigitat($this->dataStr, $q)) { - $q++; - } - $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 - + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln - - QRinput::estimateBitsMode8($q); // - 4 - l8 - if($dif < 0) { - break; - } else { - $p = $q; - } - } else if($mode == QR_MODE_AN) { - $q = $p; - while(self::isalnumat($this->dataStr, $q)) { - $q++; - } - $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 - + QRinput::estimateBitsModeAn($q - $p) + 4 + $la - - QRinput::estimateBitsMode8($q); // - 4 - l8 - if($dif < 0) { - break; - } else { - $p = $q; - } + } else if ($mode == QR_MODE_AN) { + $q = $p; + while (self::isalnumat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeAn($q - $p) + 4 + $la + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if ($dif < 0) { + break; } else { - $p++; + $p = $q; } + } else { + $p++; } + } - $run = $p; - $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); - - if($ret < 0) - return -1; + $run = $p; + $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); - return $run; - } - - //---------------------------------------------------------------------- - public function splitString() - { - while (strlen($this->dataStr) > 0) - { - if($this->dataStr == '') - return 0; - - $mode = $this->identifyMode(0); - - switch ($mode) { - case QR_MODE_NUM: $length = $this->eatNum(); break; - case QR_MODE_AN: $length = $this->eatAn(); break; - case QR_MODE_KANJI: - if ($hint == QR_MODE_KANJI) - $length = $this->eatKanji(); - else $length = $this->eat8(); - break; - default: $length = $this->eat8(); break; - - } + if ($ret < 0) { + return -1; + } + + return $run; + } - if($length == 0) return 0; - if($length < 0) return -1; - - $this->dataStr = substr($this->dataStr, $length); + //---------------------------------------------------------------------- + public function splitString() + { + while (strlen($this->dataStr) > 0) { + if ($this->dataStr == '') { + return 0; } - } - //---------------------------------------------------------------------- - public function toUpper() - { - $stringLen = strlen($this->dataStr); - $p = 0; - - while ($p<$stringLen) { - $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); - if($mode == QR_MODE_KANJI) { - $p += 2; - } else { - if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { - $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); + $mode = $this->identifyMode(0); + + switch ($mode) { + case QR_MODE_NUM:$length = $this->eatNum(); + break; + case QR_MODE_AN:$length = $this->eatAn(); + break; + case QR_MODE_KANJI: + if ($hint == QR_MODE_KANJI) { + $length = $this->eatKanji(); + } else { + $length = $this->eat8(); } - $p++; - } + + break; + default:$length = $this->eat8(); + break; + } - return $this->dataStr; - } + if ($length == 0) { + return 0; + } - //---------------------------------------------------------------------- - public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) - { - if(is_null($string) || $string == '\0' || $string == '') { - throw new Exception('empty string!!!'); + if ($length < 0) { + return -1; } - $split = new QRsplit($string, $input, $modeHint); - - if(!$casesensitive) - $split->toUpper(); - - return $split->splitString(); + $this->dataStr = substr($this->dataStr, $length); } } + //---------------------------------------------------------------------- + public function toUpper() + { + $stringLen = strlen($this->dataStr); + $p = 0; + while ($p < $stringLen) { + $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); + if ($mode == QR_MODE_KANJI) { + $p += 2; + } else { + if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { + $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); + } + $p++; + } + } -//---- qrrscode.php ----------------------------- + return $this->dataStr; + } + + //---------------------------------------------------------------------- + public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) + { + if (is_null($string) || $string == '\0' || $string == '') { + throw new Exception('empty string!!!'); + } + $split = new QRsplit($string, $input, $modeHint); + if (!$casesensitive) { + $split->toUpper(); + } + + return $split->splitString(); + } +} +//---- qrrscode.php ----------------------------- /* * PHP QR Code encoder * * Reed-Solomon error correction support - * + * * Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q * (libfec is released under the GNU Lesser General Public License.) * @@ -2282,195 +2312,225 @@ public static function splitStringToQRinput($string, QRinput $input, $modeHint, * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRrsItem { - - public $mm; // Bits per symbol - public $nn; // Symbols per block (= (1<= $this->nn) { - $x -= $this->nn; - $x = ($x >> $this->mm) + ($x & $this->nn); - } - - return $x; - } - - //---------------------------------------------------------------------- - public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) - { - // Common code for intializing a Reed-Solomon control block (char or int symbols) - // Copyright 2004 Phil Karn, KA9Q - // May be used under the terms of the GNU Lesser General Public License (LGPL) - $rs = null; - - // Check parameter ranges - if($symsize < 0 || $symsize > 8) return $rs; - if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs; - if($prim <= 0 || $prim >= (1<<$symsize)) return $rs; - if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values! - if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding - - $rs = new QRrsItem(); - $rs->mm = $symsize; - $rs->nn = (1<<$symsize)-1; - $rs->pad = $pad; - - $rs->alpha_to = array_fill(0, $rs->nn+1, 0); - $rs->index_of = array_fill(0, $rs->nn+1, 0); - - // PHP style macro replacement ;) - $NN =& $rs->nn; - $A0 =& $NN; - - // Generate Galois field lookup tables - $rs->index_of[0] = $A0; // log(zero) = -inf - $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 - $sr = 1; - - for($i=0; $i<$rs->nn; $i++) { - $rs->index_of[$sr] = $i; - $rs->alpha_to[$i] = $sr; - $sr <<= 1; - if($sr & (1<<$symsize)) { - $sr ^= $gfpoly; - } - $sr &= $rs->nn; - } - - if($sr != 1){ - // field generator polynomial is not primitive! - $rs = NULL; - return $rs; - } - - /* Form RS code generator polynomial from its roots */ - $rs->genpoly = array_fill(0, $nroots+1, 0); - - $rs->fcr = $fcr; - $rs->prim = $prim; - $rs->nroots = $nroots; - $rs->gfpoly = $gfpoly; - - /* Find prim-th root of 1, used in decoding */ - for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn) - ; // intentional empty-body loop! - - $rs->iprim = (int)($iprim / $prim); - $rs->genpoly[0] = 1; - - for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) { - $rs->genpoly[$i+1] = 1; - - // Multiply rs->genpoly[] by @**(root + x) - for ($j = $i; $j > 0; $j--) { - if ($rs->genpoly[$j] != 0) { - $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; - } else { - $rs->genpoly[$j] = $rs->genpoly[$j-1]; - } - } - // rs->genpoly[0] can never be zero - $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; +class QRrsItem +{ + + public $mm; // Bits per symbol + public $nn; // Symbols per block (= (1<= $this->nn) { + $x -= $this->nn; + $x = ($x >> $this->mm) + ($x & $this->nn); + } + + return $x; + } + + //---------------------------------------------------------------------- + public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + // Common code for intializing a Reed-Solomon control block (char or int symbols) + // Copyright 2004 Phil Karn, KA9Q + // May be used under the terms of the GNU Lesser General Public License (LGPL) + + $rs = null; + + // Check parameter ranges + if ($symsize < 0 || $symsize > 8) { + return $rs; + } + + if ($fcr < 0 || $fcr >= (1 << $symsize)) { + return $rs; + } + + if ($prim <= 0 || $prim >= (1 << $symsize)) { + return $rs; + } + + if ($nroots < 0 || $nroots >= (1 << $symsize)) { + return $rs; + } + // Can't have more roots than symbol values! + if ($pad < 0 || $pad >= ((1 << $symsize) - 1 - $nroots)) { + return $rs; + } + // Too much padding + + $rs = new QRrsItem(); + $rs->mm = $symsize; + $rs->nn = (1 << $symsize) - 1; + $rs->pad = $pad; + + $rs->alpha_to = array_fill(0, $rs->nn + 1, 0); + $rs->index_of = array_fill(0, $rs->nn + 1, 0); + + // PHP style macro replacement ;) + $NN = &$rs->nn; + $A0 = &$NN; + + // Generate Galois field lookup tables + $rs->index_of[0] = $A0; // log(zero) = -inf + $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 + $sr = 1; + + for ($i = 0; $i < $rs->nn; $i++) { + $rs->index_of[$sr] = $i; + $rs->alpha_to[$i] = $sr; + $sr <<= 1; + if ($sr & (1 << $symsize)) { + $sr ^= $gfpoly; } - - // convert rs->genpoly[] to index form for quicker encoding - for ($i = 0; $i <= $nroots; $i++) - $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; + $sr &= $rs->nn; + } + if ($sr != 1) { + // field generator polynomial is not primitive! + $rs = null; return $rs; } - - //---------------------------------------------------------------------- - public function encode_rs_char($data, &$parity) - { - $MM =& $this->mm; - $NN =& $this->nn; - $ALPHA_TO =& $this->alpha_to; - $INDEX_OF =& $this->index_of; - $GENPOLY =& $this->genpoly; - $NROOTS =& $this->nroots; - $FCR =& $this->fcr; - $PRIM =& $this->prim; - $IPRIM =& $this->iprim; - $PAD =& $this->pad; - $A0 =& $NN; - - $parity = array_fill(0, $NROOTS, 0); - - for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) { - - $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; - if($feedback != $A0) { - // feedback term is non-zero - - // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must - // always be for the polynomials constructed by init_rs() - $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); - - for($j=1;$j<$NROOTS;$j++) { - $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])]; - } - } - - // Shift - array_shift($parity); - if($feedback != $A0) { - array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); + + /* Form RS code generator polynomial from its roots */ + $rs->genpoly = array_fill(0, $nroots + 1, 0); + + $rs->fcr = $fcr; + $rs->prim = $prim; + $rs->nroots = $nroots; + $rs->gfpoly = $gfpoly; + + /* Find prim-th root of 1, used in decoding */ + for ($iprim = 1; ($iprim % $prim) != 0; $iprim += $rs->nn) + ; // intentional empty-body loop! + + $rs->iprim = (int) ($iprim / $prim); + $rs->genpoly[0] = 1; + + for ($i = 0, $root = $fcr * $prim; $i < $nroots; $i++, $root += $prim) { + $rs->genpoly[$i + 1] = 1; + + // Multiply rs->genpoly[] by @**(root + x) + for ($j = $i; $j > 0; $j--) { + if ($rs->genpoly[$j] != 0) { + $rs->genpoly[$j] = $rs->genpoly[$j - 1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; } else { - array_push($parity, 0); + $rs->genpoly[$j] = $rs->genpoly[$j - 1]; } } - } - } - - //########################################################################## - - class QRrs { - - public static $items = array(); - - //---------------------------------------------------------------------- - public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) - { - foreach(self::$items as $rs) { - if($rs->pad != $pad) continue; - if($rs->nroots != $nroots) continue; - if($rs->mm != $symsize) continue; - if($rs->gfpoly != $gfpoly) continue; - if($rs->fcr != $fcr) continue; - if($rs->prim != $prim) continue; + // rs->genpoly[0] can never be zero + $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; + } + + // convert rs->genpoly[] to index form for quicker encoding + for ($i = 0; $i <= $nroots; $i++) { + $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; + } + + return $rs; + } + + //---------------------------------------------------------------------- + public function encode_rs_char($data, &$parity) + { + $MM = &$this->mm; + $NN = &$this->nn; + $ALPHA_TO = &$this->alpha_to; + $INDEX_OF = &$this->index_of; + $GENPOLY = &$this->genpoly; + $NROOTS = &$this->nroots; + $FCR = &$this->fcr; + $PRIM = &$this->prim; + $IPRIM = &$this->iprim; + $PAD = &$this->pad; + $A0 = &$NN; + + $parity = array_fill(0, $NROOTS, 0); + + for ($i = 0; $i < ($NN - $NROOTS - $PAD); $i++) { + + $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; + if ($feedback != $A0) { + // feedback term is non-zero + + // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must + // always be for the polynomials constructed by init_rs() + $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); + + for ($j = 1; $j < $NROOTS; $j++) { + $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS - $j])]; + } + } + + // Shift + array_shift($parity); + if ($feedback != $A0) { + array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); + } else { + array_push($parity, 0); + } + } + } +} + +//########################################################################## + +class QRrs +{ + + public static $items = array(); + + //---------------------------------------------------------------------- + public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + foreach (self::$items as $rs) { + if ($rs->pad != $pad) { + continue; + } + + if ($rs->nroots != $nroots) { + continue; + } + + if ($rs->mm != $symsize) { + continue; + } - return $rs; + if ($rs->gfpoly != $gfpoly) { + continue; } - $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad); - array_unshift(self::$items, $rs); + if ($rs->fcr != $fcr) { + continue; + } + + if ($rs->prim != $prim) { + continue; + } return $rs; } - } + $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad); + array_unshift(self::$items, $rs); + return $rs; + } +} //---- qrmask.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -2496,316 +2556,324 @@ public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('N1', 3); - define('N2', 3); - define('N3', 40); - define('N4', 10); - - class QRmask { - - public $runLength = array(); - - //---------------------------------------------------------------------- - public function __construct() - { - $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); - } - - //---------------------------------------------------------------------- - public function writeFormatInformation($width, &$frame, $mask, $level) - { - $blacks = 0; - $format = QRspec::getFormatInfo($mask, $level); - for($i=0; $i<8; $i++) { - if($format & 1) { - $blacks += 2; - $v = 0x85; - } else { - $v = 0x84; - } - - $frame[8][$width - 1 - $i] = chr($v); - if($i < 6) { - $frame[$i][8] = chr($v); - } else { - $frame[$i + 1][8] = chr($v); - } - $format = $format >> 1; +define('N1', 3); +define('N2', 3); +define('N3', 40); +define('N4', 10); + +class QRmask +{ + + public $runLength = array(); + + //---------------------------------------------------------------------- + public function __construct() + { + $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); + } + + //---------------------------------------------------------------------- + public function writeFormatInformation($width, &$frame, $mask, $level) + { + $blacks = 0; + $format = QRspec::getFormatInfo($mask, $level); + + for ($i = 0; $i < 8; $i++) { + if ($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; } - - for($i=0; $i<7; $i++) { - if($format & 1) { - $blacks += 2; - $v = 0x85; - } else { - $v = 0x84; - } - - $frame[$width - 7 + $i][8] = chr($v); - if($i == 0) { - $frame[8][7] = chr($v); - } else { - $frame[8][6 - $i] = chr($v); - } - - $format = $format >> 1; - } - - return $blacks; - } - - //---------------------------------------------------------------------- - public function mask0($x, $y) { return ($x+$y)&1; } - public function mask1($x, $y) { return ($y&1); } - public function mask2($x, $y) { return ($x%3); } - public function mask3($x, $y) { return ($x+$y)%3; } - public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; } - public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; } - public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; } - public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; } - - //---------------------------------------------------------------------- - private function generateMaskNo($maskNo, $width, $frame) - { - $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); - - for($y=0; $y<$width; $y++) { - for($x=0; $x<$width; $x++) { - if(ord($frame[$y][$x]) & 0x80) { - $bitMask[$y][$x] = 0; - } else { - $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y); - $bitMask[$y][$x] = ($maskFunc == 0)?1:0; - } - - } + + $frame[8][$width - 1 - $i] = chr($v); + if ($i < 6) { + $frame[$i][8] = chr($v); + } else { + $frame[$i + 1][8] = chr($v); } - - return $bitMask; - } - - //---------------------------------------------------------------------- - public static function serial($bitFrame) - { - $codeArr = array(); - - foreach ($bitFrame as $line) - $codeArr[] = join('', $line); - - return gzcompress(join("\n", $codeArr), 9); - } - - //---------------------------------------------------------------------- - public static function unserial($code) - { - $codeArr = array(); - - $codeLines = explode("\n", gzuncompress($code)); - foreach ($codeLines as $line) - $codeArr[] = str_split($line); - - return $codeArr; - } - - //---------------------------------------------------------------------- - public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) - { - $b = 0; - $bitMask = array(); - - $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat'; + $format = $format >> 1; + } - if (QR_CACHEABLE) { - if (file_exists($fileName)) { - $bitMask = self::unserial(file_get_contents($fileName)); - } else { - $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); - if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) - mkdir(QR_CACHE_DIR.'mask_'.$maskNo); - file_put_contents($fileName, self::serial($bitMask)); - } + for ($i = 0; $i < 7; $i++) { + if ($format & 1) { + $blacks += 2; + $v = 0x85; } else { - $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + $v = 0x84; } - if ($maskGenOnly) - return; - - $d = $s; + $frame[$width - 7 + $i][8] = chr($v); + if ($i == 0) { + $frame[8][7] = chr($v); + } else { + $frame[8][6 - $i] = chr($v); + } - for($y=0; $y<$width; $y++) { - for($x=0; $x<$width; $x++) { - if($bitMask[$y][$x] == 1) { - $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]); - } - $b += (int)(ord($d[$y][$x]) & 1); + $format = $format >> 1; + } + + return $blacks; + } + + //---------------------------------------------------------------------- + public function mask0($x, $y) + {return ($x + $y) & 1;} + public function mask1($x, $y) + {return ($y & 1);} + public function mask2($x, $y) + {return ($x % 3);} + public function mask3($x, $y) + {return ($x + $y) % 3;} + public function mask4($x, $y) + {return (((int) ($y / 2)) + ((int) ($x / 3))) & 1;} + public function mask5($x, $y) + {return (($x * $y) & 1) + ($x * $y) % 3;} + public function mask6($x, $y) + {return ((($x * $y) & 1) + ($x * $y) % 3) & 1;} + public function mask7($x, $y) + {return ((($x * $y) % 3) + (($x + $y) & 1)) & 1;} + + //---------------------------------------------------------------------- + private function generateMaskNo($maskNo, $width, $frame) + { + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { + if (ord($frame[$y][$x]) & 0x80) { + $bitMask[$y][$x] = 0; + } else { + $maskFunc = call_user_func(array($this, 'mask' . $maskNo), $x, $y); + $bitMask[$y][$x] = ($maskFunc == 0) ? 1 : 0; } + } + } + + return $bitMask; + } - return $b; + //---------------------------------------------------------------------- + public static function serial($bitFrame) + { + $codeArr = array(); + + foreach ($bitFrame as $line) { + $codeArr[] = join('', $line); } - - //---------------------------------------------------------------------- - public function makeMask($width, $frame, $maskNo, $level) - { - $masked = array_fill(0, $width, str_repeat("\0", $width)); - $this->makeMaskNo($maskNo, $width, $frame, $masked); - $this->writeFormatInformation($width, $masked, $maskNo, $level); - - return $masked; + + return gzcompress(join("\n", $codeArr), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + $codeArr = array(); + + $codeLines = explode("\n", gzuncompress($code)); + foreach ($codeLines as $line) { + $codeArr[] = str_split($line); } - - //---------------------------------------------------------------------- - public function calcN1N3($length) - { - $demerit = 0; - for($i=0; $i<$length; $i++) { - - if($this->runLength[$i] >= 5) { - $demerit += (N1 + ($this->runLength[$i] - 5)); + return $codeArr; + } + + //---------------------------------------------------------------------- + public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) + { + $b = 0; + $bitMask = array(); + + $fileName = QR_CACHE_DIR . 'mask_' . $maskNo . DIRECTORY_SEPARATOR . 'mask_' . $width . '_' . $maskNo . '.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + $bitMask = self::unserial(file_get_contents($fileName)); + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + if (!file_exists(QR_CACHE_DIR . 'mask_' . $maskNo)) { + mkdir(QR_CACHE_DIR . 'mask_' . $maskNo); + } + + file_put_contents($fileName, self::serial($bitMask)); + } + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + } + + if ($maskGenOnly) { + return; + } + + $d = $s; + + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { + if ($bitMask[$y][$x] == 1) { + $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int) $bitMask[$y][$x]); } - if($i & 1) { - if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) { - $fact = (int)($this->runLength[$i] / 3); - if(($this->runLength[$i-2] == $fact) && - ($this->runLength[$i-1] == $fact) && - ($this->runLength[$i+1] == $fact) && - ($this->runLength[$i+2] == $fact)) { - if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) { - $demerit += N3; - } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) { - $demerit += N3; - } + $b += (int) (ord($d[$y][$x]) & 1); + } + } + + return $b; + } + + //---------------------------------------------------------------------- + public function makeMask($width, $frame, $maskNo, $level) + { + $masked = array_fill(0, $width, str_repeat("\0", $width)); + $this->makeMaskNo($maskNo, $width, $frame, $masked); + $this->writeFormatInformation($width, $masked, $maskNo, $level); + + return $masked; + } + + //---------------------------------------------------------------------- + public function calcN1N3($length) + { + $demerit = 0; + + for ($i = 0; $i < $length; $i++) { + + if ($this->runLength[$i] >= 5) { + $demerit += (N1 + ($this->runLength[$i] - 5)); + } + if ($i & 1) { + if (($i >= 3) && ($i < ($length - 2)) && ($this->runLength[$i] % 3 == 0)) { + $fact = (int) ($this->runLength[$i] / 3); + if (($this->runLength[$i - 2] == $fact) && + ($this->runLength[$i - 1] == $fact) && + ($this->runLength[$i + 1] == $fact) && + ($this->runLength[$i + 2] == $fact)) { + if (($this->runLength[$i - 3] < 0) || ($this->runLength[$i - 3] >= (4 * $fact))) { + $demerit += N3; + } else if ((($i + 3) >= $length) || ($this->runLength[$i + 3] >= (4 * $fact))) { + $demerit += N3; } } } } - return $demerit; } - - //---------------------------------------------------------------------- - public function evaluateSymbol($width, $frame) - { + return $demerit; + } + + //---------------------------------------------------------------------- + public function evaluateSymbol($width, $frame) + { + $head = 0; + $demerit = 0; + + for ($y = 0; $y < $width; $y++) { $head = 0; - $demerit = 0; + $this->runLength[0] = 1; - for($y=0; $y<$width; $y++) { - $head = 0; - $this->runLength[0] = 1; - - $frameY = $frame[$y]; - - if ($y>0) - $frameYM = $frame[$y-1]; - - for($x=0; $x<$width; $x++) { - if(($x > 0) && ($y > 0)) { - $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]); - $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]); - - if(($b22 | ($w22 ^ 1))&1) { - $demerit += N2; - } + $frameY = $frame[$y]; + + if ($y > 0) { + $frameYM = $frame[$y - 1]; + } + + for ($x = 0; $x < $width; $x++) { + if (($x > 0) && ($y > 0)) { + $b22 = ord($frameY[$x]) & ord($frameY[$x - 1]) & ord($frameYM[$x]) & ord($frameYM[$x - 1]); + $w22 = ord($frameY[$x]) | ord($frameY[$x - 1]) | ord($frameYM[$x]) | ord($frameYM[$x - 1]); + + if (($b22 | ($w22 ^ 1)) & 1) { + $demerit += N2; } - if(($x == 0) && (ord($frameY[$x]) & 1)) { - $this->runLength[0] = -1; - $head = 1; + } + if (($x == 0) && (ord($frameY[$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if ($x > 0) { + if ((ord($frameY[$x]) ^ ord($frameY[$x - 1])) & 1) { + $head++; $this->runLength[$head] = 1; - } else if($x > 0) { - if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) { - $head++; - $this->runLength[$head] = 1; - } else { - $this->runLength[$head]++; - } + } else { + $this->runLength[$head]++; } } - - $demerit += $this->calcN1N3($head+1); - } - - for($x=0; $x<$width; $x++) { - $head = 0; - $this->runLength[0] = 1; - - for($y=0; $y<$width; $y++) { - if($y == 0 && (ord($frame[$y][$x]) & 1)) { - $this->runLength[0] = -1; - $head = 1; + } + + $demerit += $this->calcN1N3($head + 1); + } + + for ($x = 0; $x < $width; $x++) { + $head = 0; + $this->runLength[0] = 1; + + for ($y = 0; $y < $width; $y++) { + if ($y == 0 && (ord($frame[$y][$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if ($y > 0) { + if ((ord($frame[$y][$x]) ^ ord($frame[$y - 1][$x])) & 1) { + $head++; $this->runLength[$head] = 1; - } else if($y > 0) { - if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) { - $head++; - $this->runLength[$head] = 1; - } else { - $this->runLength[$head]++; - } + } else { + $this->runLength[$head]++; } } - - $demerit += $this->calcN1N3($head+1); - } - - return $demerit; - } - - - //---------------------------------------------------------------------- - public function mask($width, $frame, $level) - { - $minDemerit = PHP_INT_MAX; - $bestMaskNum = 0; - $bestMask = array(); - - $checked_masks = array(0,1,2,3,4,5,6,7); - - if (QR_FIND_FROM_RANDOM !== false) { - - $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9); - for ($i = 0; $i < $howManuOut; $i++) { - $remPos = rand (0, count($checked_masks)-1); - unset($checked_masks[$remPos]); - $checked_masks = array_values($checked_masks); - } - - } - - $bestMask = $frame; - - foreach($checked_masks as $i) { - $mask = array_fill(0, $width, str_repeat("\0", $width)); - - $demerit = 0; - $blacks = 0; - $blacks = $this->makeMaskNo($i, $width, $frame, $mask); - $blacks += $this->writeFormatInformation($width, $mask, $i, $level); - $blacks = (int)(100 * $blacks / ($width * $width)); - $demerit = (int)((int)(abs($blacks - 50) / 5) * N4); - $demerit += $this->evaluateSymbol($width, $mask); - - if($demerit < $minDemerit) { - $minDemerit = $demerit; - $bestMask = $mask; - $bestMaskNum = $i; - } } - - return $bestMask; + + $demerit += $this->calcN1N3($head + 1); } - - //---------------------------------------------------------------------- + + return $demerit; } + //---------------------------------------------------------------------- + public function mask($width, $frame, $level) + { + $minDemerit = PHP_INT_MAX; + $bestMaskNum = 0; + $bestMask = array(); + $checked_masks = array(0, 1, 2, 3, 4, 5, 6, 7); + if (QR_FIND_FROM_RANDOM !== false) { -//---- qrencode.php ----------------------------- + $howManuOut = 8 - (QR_FIND_FROM_RANDOM % 9); + for ($i = 0; $i < $howManuOut; $i++) { + $remPos = rand(0, count($checked_masks) - 1); + unset($checked_masks[$remPos]); + $checked_masks = array_values($checked_masks); + } + + } + + $bestMask = $frame; + + foreach ($checked_masks as $i) { + $mask = array_fill(0, $width, str_repeat("\0", $width)); + + $demerit = 0; + $blacks = 0; + $blacks = $this->makeMaskNo($i, $width, $frame, $mask); + $blacks += $this->writeFormatInformation($width, $mask, $i, $level); + $blacks = (int) (100 * $blacks / ($width * $width)); + $demerit = (int) ((int) (abs($blacks - 50) / 5) * N4); + $demerit += $this->evaluateSymbol($width, $mask); + if ($demerit < $minDemerit) { + $minDemerit = $demerit; + $bestMask = $mask; + $bestMaskNum = $i; + } + } + + return $bestMask; + } + //---------------------------------------------------------------------- +} +//---- qrencode.php ----------------------------- /* * PHP QR Code encoder @@ -2832,481 +2900,492 @@ public function mask($width, $frame, $level) * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRrsblock { - public $dataLength; - public $data = array(); - public $eccLength; - public $ecc = array(); - - public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) - { - $rs->encode_rs_char($data, $ecc); - - $this->dataLength = $dl; - $this->data = $data; - $this->eccLength = $el; - $this->ecc = $ecc; - } - }; - - //########################################################################## - - class QRrawcode { - public $version; - public $datacode = array(); - public $ecccode = array(); - public $blocks; - public $rsblocks = array(); //of RSblock - public $count; - public $dataLength; - public $eccLength; - public $b1; - - //---------------------------------------------------------------------- - public function __construct(QRinput $input) - { - $spec = array(0,0,0,0,0); - - $this->datacode = $input->getByteStream(); - if(is_null($this->datacode)) { - throw new Exception('null imput string'); - } - - QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec); - - $this->version = $input->getVersion(); - $this->b1 = QRspec::rsBlockNum1($spec); - $this->dataLength = QRspec::rsDataLength($spec); - $this->eccLength = QRspec::rsEccLength($spec); - $this->ecccode = array_fill(0, $this->eccLength, 0); - $this->blocks = QRspec::rsBlockNum($spec); - - $ret = $this->init($spec); - if($ret < 0) { - throw new Exception('block alloc error'); - return null; - } - $this->count = 0; +class QRrsblock +{ + public $dataLength; + public $data = array(); + public $eccLength; + public $ecc = array(); + + public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) + { + $rs->encode_rs_char($data, $ecc); + + $this->dataLength = $dl; + $this->data = $data; + $this->eccLength = $el; + $this->ecc = $ecc; + } +}; + +//########################################################################## + +class QRrawcode +{ + public $version; + public $datacode = array(); + public $ecccode = array(); + public $blocks; + public $rsblocks = array(); //of RSblock + public $count; + public $dataLength; + public $eccLength; + public $b1; + + //---------------------------------------------------------------------- + public function __construct(QRinput $input) + { + $spec = array(0, 0, 0, 0, 0); + + $this->datacode = $input->getByteStream(); + if (is_null($this->datacode)) { + throw new Exception('null imput string'); } - - //---------------------------------------------------------------------- - public function init(array $spec) - { - $dl = QRspec::rsDataCodes1($spec); - $el = QRspec::rsEccCodes1($spec); - $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); - - $blockNo = 0; - $dataPos = 0; - $eccPos = 0; - for($i=0; $iecccode,$eccPos); - $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); - $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); - - $dataPos += $dl; - $eccPos += $el; - $blockNo++; - } + QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec); - if(QRspec::rsBlockNum2($spec) == 0) - return 0; + $this->version = $input->getVersion(); + $this->b1 = QRspec::rsBlockNum1($spec); + $this->dataLength = QRspec::rsDataLength($spec); + $this->eccLength = QRspec::rsEccLength($spec); + $this->ecccode = array_fill(0, $this->eccLength, 0); + $this->blocks = QRspec::rsBlockNum($spec); - $dl = QRspec::rsDataCodes2($spec); - $el = QRspec::rsEccCodes2($spec); - $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); - - if($rs == NULL) return -1; - - for($i=0; $iecccode,$eccPos); - $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); - $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); - - $dataPos += $dl; - $eccPos += $el; - $blockNo++; - } + $ret = $this->init($spec); + if ($ret < 0) { + throw new Exception('block alloc error'); + return null; + } + $this->count = 0; + } + + //---------------------------------------------------------------------- + public function init(array $spec) + { + $dl = QRspec::rsDataCodes1($spec); + $el = QRspec::rsEccCodes1($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + $blockNo = 0; + $dataPos = 0; + $eccPos = 0; + for ($i = 0; $i < QRspec::rsBlockNum1($spec); $i++) { + $ecc = array_slice($this->ecccode, $eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + if (QRspec::rsBlockNum2($spec) == 0) { return 0; } - - //---------------------------------------------------------------------- - public function getCode() - { - $ret; - - if($this->count < $this->dataLength) { - $row = $this->count % $this->blocks; - $col = $this->count / $this->blocks; - if($col >= $this->rsblocks[0]->dataLength) { - $row += $this->b1; - } - $ret = $this->rsblocks[$row]->data[$col]; - } else if($this->count < $this->dataLength + $this->eccLength) { - $row = ($this->count - $this->dataLength) % $this->blocks; - $col = ($this->count - $this->dataLength) / $this->blocks; - $ret = $this->rsblocks[$row]->ecc[$col]; - } else { - return 0; - } - $this->count++; - - return $ret; + + $dl = QRspec::rsDataCodes2($spec); + $el = QRspec::rsEccCodes2($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + if ($rs == null) { + return -1; + } + + for ($i = 0; $i < QRspec::rsBlockNum2($spec); $i++) { + $ecc = array_slice($this->ecccode, $eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; } + + return 0; } - //########################################################################## - - class QRcode { - - public $version; - public $width; - public $data; - - //---------------------------------------------------------------------- - public function encodeMask(QRinput $input, $mask) - { - if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { - throw new Exception('wrong version'); - } - if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { - throw new Exception('wrong level'); - } - - $raw = new QRrawcode($input); - - QRtools::markTime('after_raw'); - - $version = $raw->version; - $width = QRspec::getWidth($version); - $frame = QRspec::newFrame($version); - - $filler = new FrameFiller($width, $frame); - if(is_null($filler)) { - return NULL; - } - - // inteleaved data and ecc codes - for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) { - $code = $raw->getCode(); - $bit = 0x80; - for($j=0; $j<8; $j++) { - $addr = $filler->next(); - $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); - $bit = $bit >> 1; - } - } - - QRtools::markTime('after_filler'); - - unset($raw); - - // remainder bits - $j = QRspec::getRemainder($version); - for($i=0; $i<$j; $i++) { - $addr = $filler->next(); - $filler->setFrameAt($addr, 0x02); - } - - $frame = $filler->frame; - unset($filler); - - - // masking - $maskObj = new QRmask(); - if($mask < 0) { - - if (QR_FIND_BEST_MASK) { - $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); - } else { - $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel()); - } - } else { - $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); - } - - if($masked == NULL) { - return NULL; - } - - QRtools::markTime('after_mask'); - - $this->version = $version; - $this->width = $width; - $this->data = $masked; - - return $this; - } - - //---------------------------------------------------------------------- - public function encodeInput(QRinput $input) - { - return $this->encodeMask($input, -1); - } - - //---------------------------------------------------------------------- - public function encodeString8bit($string, $version, $level) - { - if(string == NULL) { - throw new Exception('empty string!'); - return NULL; - } - - $input = new QRinput($version, $level); - if($input == NULL) return NULL; - - $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); - if($ret < 0) { - unset($input); - return NULL; - } - return $this->encodeInput($input); - } - - //---------------------------------------------------------------------- - public function encodeString($string, $version, $level, $hint, $casesensitive) - { - - if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { - throw new Exception('bad hint'); - return NULL; - } - - $input = new QRinput($version, $level); - if($input == NULL) return NULL; - - $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); - if($ret < 0) { - return NULL; - } - - return $this->encodeInput($input); - } - - //---------------------------------------------------------------------- - public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false) - { - $enc = QRencode::factory($level, $size, $margin); - return $enc->encodePNG($text, $outfile, $saveandprint=false); - } - - //---------------------------------------------------------------------- - public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) - { - $enc = QRencode::factory($level, $size, $margin); - return $enc->encode($text, $outfile); - } - - //---------------------------------------------------------------------- - public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) - { - $enc = QRencode::factory($level, $size, $margin); - return $enc->encodeRAW($text, $outfile); - } - } - - //########################################################################## - - class FrameFiller { - - public $width; - public $frame; - public $x; - public $y; - public $dir; - public $bit; - - //---------------------------------------------------------------------- - public function __construct($width, &$frame) - { - $this->width = $width; - $this->frame = $frame; - $this->x = $width - 1; - $this->y = $width - 1; - $this->dir = -1; - $this->bit = -1; - } - - //---------------------------------------------------------------------- - public function setFrameAt($at, $val) - { - $this->frame[$at['y']][$at['x']] = chr($val); - } - - //---------------------------------------------------------------------- - public function getFrameAt($at) - { - return ord($this->frame[$at['y']][$at['x']]); - } - - //---------------------------------------------------------------------- - public function next() - { - do { - - if($this->bit == -1) { - $this->bit = 0; - return array('x'=>$this->x, 'y'=>$this->y); - } + //---------------------------------------------------------------------- + public function getCode() + { + $ret; + + if ($this->count < $this->dataLength) { + $row = $this->count % $this->blocks; + $col = $this->count / $this->blocks; + if ($col >= $this->rsblocks[0]->dataLength) { + $row += $this->b1; + } + $ret = $this->rsblocks[$row]->data[$col]; + } else if ($this->count < $this->dataLength + $this->eccLength) { + $row = ($this->count - $this->dataLength) % $this->blocks; + $col = ($this->count - $this->dataLength) / $this->blocks; + $ret = $this->rsblocks[$row]->ecc[$col]; + } else { + return 0; + } + $this->count++; - $x = $this->x; - $y = $this->y; - $w = $this->width; + return $ret; + } +} - if($this->bit == 0) { - $x--; - $this->bit++; - } else { - $x++; - $y += $this->dir; - $this->bit--; - } +//########################################################################## - if($this->dir < 0) { - if($y < 0) { - $y = 0; - $x -= 2; - $this->dir = 1; - if($x == 6) { - $x--; - $y = 9; - } - } - } else { - if($y == $w) { - $y = $w - 1; - $x -= 2; - $this->dir = -1; - if($x == 6) { - $x--; - $y -= 8; - } - } - } - if($x < 0 || $y < 0) return null; - - $this->x = $x; - $this->y = $y; - - } while(ord($this->frame[$y][$x]) & 0x80); - - return array('x'=>$x, 'y'=>$y); - } - - } ; - - //########################################################################## - - class QRencode { - - public $casesensitive = true; - public $eightbit = false; - - public $version = 0; - public $size = 3; - public $margin = 4; - - public $structured = 0; // not supported yet - - public $level = QR_ECLEVEL_L; - public $hint = QR_MODE_8; - - //---------------------------------------------------------------------- - public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) - { - $enc = new QRencode(); - $enc->size = $size; - $enc->margin = $margin; - - switch ($level.'') { - case '0': - case '1': - case '2': - case '3': - $enc->level = $level; - break; - case 'l': - case 'L': - $enc->level = QR_ECLEVEL_L; - break; - case 'm': - case 'M': - $enc->level = QR_ECLEVEL_M; - break; - case 'q': - case 'Q': - $enc->level = QR_ECLEVEL_Q; - break; - case 'h': - case 'H': - $enc->level = QR_ECLEVEL_H; - break; +class QRcode +{ + + public $version; + public $width; + public $data; + + //---------------------------------------------------------------------- + public function encodeMask(QRinput $input, $mask) + { + if ($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { + throw new Exception('wrong version'); + } + if ($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { + throw new Exception('wrong level'); + } + + $raw = new QRrawcode($input); + + QRtools::markTime('after_raw'); + + $version = $raw->version; + $width = QRspec::getWidth($version); + $frame = QRspec::newFrame($version); + + $filler = new FrameFiller($width, $frame); + if (is_null($filler)) { + return null; + } + + // inteleaved data and ecc codes + for ($i = 0; $i < $raw->dataLength + $raw->eccLength; $i++) { + $code = $raw->getCode(); + $bit = 0x80; + for ($j = 0; $j < 8; $j++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); + $bit = $bit >> 1; } - - return $enc; } - - //---------------------------------------------------------------------- - public function encodeRAW($intext, $outfile = false) - { - $code = new QRcode(); - if($this->eightbit) { - $code->encodeString8bit($intext, $this->version, $this->level); + QRtools::markTime('after_filler'); + + unset($raw); + + // remainder bits + $j = QRspec::getRemainder($version); + for ($i = 0; $i < $j; $i++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02); + } + + $frame = $filler->frame; + unset($filler); + + // masking + $maskObj = new QRmask(); + if ($mask < 0) { + + if (QR_FIND_BEST_MASK) { + $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); } else { - $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel()); } - - return $code->data; + } else { + $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); } - //---------------------------------------------------------------------- - public function encode($intext, $outfile = false) - { - $code = new QRcode(); + if ($masked == null) { + return null; + } - if($this->eightbit) { - $code->encodeString8bit($intext, $this->version, $this->level); - } else { - $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + QRtools::markTime('after_mask'); + + $this->version = $version; + $this->width = $width; + $this->data = $masked; + + return $this; + } + + //---------------------------------------------------------------------- + public function encodeInput(QRinput $input) + { + return $this->encodeMask($input, -1); + } + + //---------------------------------------------------------------------- + public function encodeString8bit($string, $version, $level) + { + if (string == null) { + throw new Exception('empty string!'); + return null; + } + + $input = new QRinput($version, $level); + if ($input == null) { + return null; + } + + $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); + if ($ret < 0) { + unset($input); + return null; + } + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public function encodeString($string, $version, $level, $hint, $casesensitive) + { + + if ($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { + throw new Exception('bad hint'); + return null; + } + + $input = new QRinput($version, $level); + if ($input == null) { + return null; + } + + $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); + if ($ret < 0) { + return null; + } + + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint = false) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodePNG($text, $outfile, $saveandprint = false); + } + + //---------------------------------------------------------------------- + public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encode($text, $outfile); + } + + //---------------------------------------------------------------------- + public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodeRAW($text, $outfile); + } +} + +//########################################################################## + +class FrameFiller +{ + + public $width; + public $frame; + public $x; + public $y; + public $dir; + public $bit; + + //---------------------------------------------------------------------- + public function __construct($width, &$frame) + { + $this->width = $width; + $this->frame = $frame; + $this->x = $width - 1; + $this->y = $width - 1; + $this->dir = -1; + $this->bit = -1; + } + + //---------------------------------------------------------------------- + public function setFrameAt($at, $val) + { + $this->frame[$at['y']][$at['x']] = chr($val); + } + + //---------------------------------------------------------------------- + public function getFrameAt($at) + { + return ord($this->frame[$at['y']][$at['x']]); + } + + //---------------------------------------------------------------------- + public function next() + { + do { + + if ($this->bit == -1) { + $this->bit = 0; + return array('x' => $this->x, 'y' => $this->y); } - - QRtools::markTime('after_encode'); - - if ($outfile!== false) { - file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); + + $x = $this->x; + $y = $this->y; + $w = $this->width; + + if ($this->bit == 0) { + $x--; + $this->bit++; } else { - return QRtools::binarize($code->data); + $x++; + $y += $this->dir; + $this->bit--; + } + + if ($this->dir < 0) { + if ($y < 0) { + $y = 0; + $x -= 2; + $this->dir = 1; + if ($x == 6) { + $x--; + $y = 9; + } + } + } else { + if ($y == $w) { + $y = $w - 1; + $x -= 2; + $this->dir = -1; + if ($x == 6) { + $x--; + $y -= 8; + } + } } - } - - //---------------------------------------------------------------------- - public function encodePNG($intext, $outfile = false,$saveandprint=false) - { - try { - - ob_start(); - $tab = $this->encode($intext); - $err = ob_get_contents(); - ob_end_clean(); - - if ($err != '') - QRtools::log($outfile, $err); - - $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin)); - - QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint); - - } catch (Exception $e) { - - QRtools::log($outfile, $e->getMessage()); - + if ($x < 0 || $y < 0) { + return null; } + + $this->x = $x; + $this->y = $y; + + } while (ord($this->frame[$y][$x]) & 0x80); + + return array('x' => $x, 'y' => $y); + } + +}; + +//########################################################################## + +class QRencode +{ + + public $casesensitive = true; + public $eightbit = false; + + public $version = 0; + public $size = 3; + public $margin = 4; + + public $structured = 0; // not supported yet + + public $level = QR_ECLEVEL_L; + public $hint = QR_MODE_8; + + //---------------------------------------------------------------------- + public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = new QRencode(); + $enc->size = $size; + $enc->margin = $margin; + + switch ($level . '') { + case '0': + case '1': + case '2': + case '3': + $enc->level = $level; + break; + case 'l': + case 'L': + $enc->level = QR_ECLEVEL_L; + break; + case 'm': + case 'M': + $enc->level = QR_ECLEVEL_M; + break; + case 'q': + case 'Q': + $enc->level = QR_ECLEVEL_Q; + break; + case 'h': + case 'H': + $enc->level = QR_ECLEVEL_H; + break; + } + + return $enc; + } + + //---------------------------------------------------------------------- + public function encodeRAW($intext, $outfile = false) + { + $code = new QRcode(); + + if ($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + return $code->data; + } + + //---------------------------------------------------------------------- + public function encode($intext, $outfile = false) + { + $code = new QRcode(); + + if ($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + QRtools::markTime('after_encode'); + + if ($outfile !== false) { + file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); + } else { + return QRtools::binarize($code->data); } } + //---------------------------------------------------------------------- + public function encodePNG($intext, $outfile = false, $saveandprint = false) + { + try { + + ob_start(); + $tab = $this->encode($intext); + $err = ob_get_contents(); + ob_end_clean(); + if ($err != '') { + QRtools::log($outfile, $err); + } + + $maxSize = (int) (QR_PNG_MAXIMUM_SIZE / (count($tab) + 2 * $this->margin)); + + QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin, $saveandprint); + + } catch (Exception $e) { + + QRtools::log($outfile, $e->getMessage()); + + } + } +} diff --git a/include/qrcode/qrbitstream.php b/include/qrcode/qrbitstream.php index c8d11661..7570982a 100755 --- a/include/qrcode/qrbitstream.php +++ b/include/qrcode/qrbitstream.php @@ -24,157 +24,162 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRbitstream { - - public $data = array(); - - //---------------------------------------------------------------------- - public function size() - { - return count($this->data); - } - - //---------------------------------------------------------------------- - public function allocate($setLength) - { - $this->data = array_fill(0, $setLength, 0); - return 0; + +class QRbitstream +{ + + public $data = array(); + + //---------------------------------------------------------------------- + public function size() + { + return count($this->data); + } + + //---------------------------------------------------------------------- + public function allocate($setLength) + { + $this->data = array_fill(0, $setLength, 0); + return 0; + } + + //---------------------------------------------------------------------- + public static function newFromNum($bits, $num) + { + $bstream = new QRbitstream(); + $bstream->allocate($bits); + + $mask = 1 << ($bits - 1); + for ($i = 0; $i < $bits; $i++) { + if ($num & $mask) { + $bstream->data[$i] = 1; + } else { + $bstream->data[$i] = 0; + } + $mask = $mask >> 1; } - - //---------------------------------------------------------------------- - public static function newFromNum($bits, $num) - { - $bstream = new QRbitstream(); - $bstream->allocate($bits); - - $mask = 1 << ($bits - 1); - for($i=0; $i<$bits; $i++) { - if($num & $mask) { - $bstream->data[$i] = 1; + + return $bstream; + } + + //---------------------------------------------------------------------- + public static function newFromBytes($size, $data) + { + $bstream = new QRbitstream(); + $bstream->allocate($size * 8); + $p = 0; + + for ($i = 0; $i < $size; $i++) { + $mask = 0x80; + for ($j = 0; $j < 8; $j++) { + if ($data[$i] & $mask) { + $bstream->data[$p] = 1; } else { - $bstream->data[$i] = 0; + $bstream->data[$p] = 0; } + $p++; $mask = $mask >> 1; } + } + + return $bstream; + } - return $bstream; + //---------------------------------------------------------------------- + public function append(QRbitstream $arg) + { + if (is_null($arg)) { + return -1; } - - //---------------------------------------------------------------------- - public static function newFromBytes($size, $data) - { - $bstream = new QRbitstream(); - $bstream->allocate($size * 8); - $p=0; - - for($i=0; $i<$size; $i++) { - $mask = 0x80; - for($j=0; $j<8; $j++) { - if($data[$i] & $mask) { - $bstream->data[$p] = 1; - } else { - $bstream->data[$p] = 0; - } - $p++; - $mask = $mask >> 1; - } - } - return $bstream; + if ($arg->size() == 0) { + return 0; } - - //---------------------------------------------------------------------- - public function append(QRbitstream $arg) - { - if (is_null($arg)) { - return -1; - } - - if($arg->size() == 0) { - return 0; - } - - if($this->size() == 0) { - $this->data = $arg->data; - return 0; - } - - $this->data = array_values(array_merge($this->data, $arg->data)); + if ($this->size() == 0) { + $this->data = $arg->data; return 0; } - - //---------------------------------------------------------------------- - public function appendNum($bits, $num) - { - if ($bits == 0) - return 0; - - $b = QRbitstream::newFromNum($bits, $num); - - if(is_null($b)) - return -1; - - $ret = $this->append($b); - unset($b); - - return $ret; + + $this->data = array_values(array_merge($this->data, $arg->data)); + + return 0; + } + + //---------------------------------------------------------------------- + public function appendNum($bits, $num) + { + if ($bits == 0) { + return 0; } - //---------------------------------------------------------------------- - public function appendBytes($size, $data) - { - if ($size == 0) - return 0; + $b = QRbitstream::newFromNum($bits, $num); - $b = QRbitstream::newFromBytes($size, $data); - - if(is_null($b)) - return -1; + if (is_null($b)) { + return -1; + } - $ret = $this->append($b); - unset($b); + $ret = $this->append($b); + unset($b); - return $ret; + return $ret; + } + + //---------------------------------------------------------------------- + public function appendBytes($size, $data) + { + if ($size == 0) { + return 0; } - - //---------------------------------------------------------------------- - public function toByte() - { - - $size = $this->size(); - - if($size == 0) { - return array(); - } - - $data = array_fill(0, (int)(($size + 7) / 8), 0); - $bytes = (int)($size / 8); - - $p = 0; - - for($i=0; $i<$bytes; $i++) { - $v = 0; - for($j=0; $j<8; $j++) { - $v = $v << 1; - $v |= $this->data[$p]; - $p++; - } - $data[$i] = $v; - } - - if($size & 7) { - $v = 0; - for($j=0; $j<($size & 7); $j++) { - $v = $v << 1; - $v |= $this->data[$p]; - $p++; - } - $data[$bytes] = $v; + + $b = QRbitstream::newFromBytes($size, $data); + + if (is_null($b)) { + return -1; + } + + $ret = $this->append($b); + unset($b); + + return $ret; + } + + //---------------------------------------------------------------------- + public function toByte() + { + + $size = $this->size(); + + if ($size == 0) { + return array(); + } + + $data = array_fill(0, (int) (($size + 7) / 8), 0); + $bytes = (int) ($size / 8); + + $p = 0; + + for ($i = 0; $i < $bytes; $i++) { + $v = 0; + for ($j = 0; $j < 8; $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; } + $data[$i] = $v; + } - return $data; + if ($size & 7) { + $v = 0; + for ($j = 0; $j < ($size & 7); $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$bytes] = $v; } + return $data; } + +} diff --git a/include/qrcode/qrconfig.php b/include/qrcode/qrconfig.php index 62e7f974..68066f6d 100755 --- a/include/qrcode/qrconfig.php +++ b/include/qrcode/qrconfig.php @@ -4,14 +4,13 @@ * * Config file, feel free to modify */ - - define('QR_CACHEABLE', true); // use cache - more disk reads but less CPU power, masks and format templates are stored there - define('QR_CACHE_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR); // used when QR_CACHEABLE === true - define('QR_LOG_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR); // default error logs dir - - define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code - define('QR_FIND_FROM_RANDOM', false); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly - define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false - - define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images - \ No newline at end of file + +define('QR_CACHEABLE', true); // use cache - more disk reads but less CPU power, masks and format templates are stored there +define('QR_CACHE_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR); // used when QR_CACHEABLE === true +define('QR_LOG_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR); // default error logs dir + +define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code +define('QR_FIND_FROM_RANDOM', false); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly +define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false + +define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images diff --git a/include/qrcode/qrconst.php b/include/qrcode/qrconst.php index 60f93af1..bbf7afb9 100755 --- a/include/qrcode/qrconst.php +++ b/include/qrcode/qrconst.php @@ -25,30 +25,32 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - // Encoding modes - - define('QR_MODE_NUL', -1); - define('QR_MODE_NUM', 0); - define('QR_MODE_AN', 1); - define('QR_MODE_8', 2); - define('QR_MODE_KANJI', 3); - define('QR_MODE_STRUCTURE', 4); - - // Levels of error correction. - - define('QR_ECLEVEL_L', 0); - define('QR_ECLEVEL_M', 1); - define('QR_ECLEVEL_Q', 2); - define('QR_ECLEVEL_H', 3); - - // Supported output formats - - define('QR_FORMAT_TEXT', 0); - define('QR_FORMAT_PNG', 1); - - class qrstr { - public static function set(&$srctab, $x, $y, $repl, $replLen = false) { - $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); - } - } \ No newline at end of file + +// Encoding modes + +define('QR_MODE_NUL', -1); +define('QR_MODE_NUM', 0); +define('QR_MODE_AN', 1); +define('QR_MODE_8', 2); +define('QR_MODE_KANJI', 3); +define('QR_MODE_STRUCTURE', 4); + +// Levels of error correction. + +define('QR_ECLEVEL_L', 0); +define('QR_ECLEVEL_M', 1); +define('QR_ECLEVEL_Q', 2); +define('QR_ECLEVEL_H', 3); + +// Supported output formats + +define('QR_FORMAT_TEXT', 0); +define('QR_FORMAT_PNG', 1); + +class qrstr +{ + public static function set(&$srctab, $x, $y, $repl, $replLen = false) + { + $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false) ? substr($repl, 0, $replLen) : $repl, $x, ($replLen !== false) ? $replLen : strlen($repl)); + } +} diff --git a/include/qrcode/qrencode.php b/include/qrcode/qrencode.php index fc909fa7..b8f547e1 100755 --- a/include/qrcode/qrencode.php +++ b/include/qrcode/qrencode.php @@ -24,479 +24,492 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRrsblock { - public $dataLength; - public $data = array(); - public $eccLength; - public $ecc = array(); - - public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) - { - $rs->encode_rs_char($data, $ecc); - - $this->dataLength = $dl; - $this->data = $data; - $this->eccLength = $el; - $this->ecc = $ecc; + +class QRrsblock +{ + public $dataLength; + public $data = array(); + public $eccLength; + public $ecc = array(); + + public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) + { + $rs->encode_rs_char($data, $ecc); + + $this->dataLength = $dl; + $this->data = $data; + $this->eccLength = $el; + $this->ecc = $ecc; + } +}; + +//########################################################################## + +class QRrawcode +{ + public $version; + public $datacode = array(); + public $ecccode = array(); + public $blocks; + public $rsblocks = array(); //of RSblock + public $count; + public $dataLength; + public $eccLength; + public $b1; + + //---------------------------------------------------------------------- + public function __construct(QRinput $input) + { + $spec = array(0, 0, 0, 0, 0); + + $this->datacode = $input->getByteStream(); + if (is_null($this->datacode)) { + throw new Exception('null imput string'); } - }; - - //########################################################################## - - class QRrawcode { - public $version; - public $datacode = array(); - public $ecccode = array(); - public $blocks; - public $rsblocks = array(); //of RSblock - public $count; - public $dataLength; - public $eccLength; - public $b1; - - //---------------------------------------------------------------------- - public function __construct(QRinput $input) - { - $spec = array(0,0,0,0,0); - - $this->datacode = $input->getByteStream(); - if(is_null($this->datacode)) { - throw new Exception('null imput string'); - } - QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec); - - $this->version = $input->getVersion(); - $this->b1 = QRspec::rsBlockNum1($spec); - $this->dataLength = QRspec::rsDataLength($spec); - $this->eccLength = QRspec::rsEccLength($spec); - $this->ecccode = array_fill(0, $this->eccLength, 0); - $this->blocks = QRspec::rsBlockNum($spec); - - $ret = $this->init($spec); - if($ret < 0) { - throw new Exception('block alloc error'); - return null; - } + QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec); - $this->count = 0; + $this->version = $input->getVersion(); + $this->b1 = QRspec::rsBlockNum1($spec); + $this->dataLength = QRspec::rsDataLength($spec); + $this->eccLength = QRspec::rsEccLength($spec); + $this->ecccode = array_fill(0, $this->eccLength, 0); + $this->blocks = QRspec::rsBlockNum($spec); + + $ret = $this->init($spec); + if ($ret < 0) { + throw new Exception('block alloc error'); + return null; } - - //---------------------------------------------------------------------- - public function init(array $spec) - { - $dl = QRspec::rsDataCodes1($spec); - $el = QRspec::rsEccCodes1($spec); - $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); - - - $blockNo = 0; - $dataPos = 0; - $eccPos = 0; - for($i=0; $iecccode,$eccPos); - $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); - $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); - - $dataPos += $dl; - $eccPos += $el; - $blockNo++; - } - if(QRspec::rsBlockNum2($spec) == 0) - return 0; - - $dl = QRspec::rsDataCodes2($spec); - $el = QRspec::rsEccCodes2($spec); - $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); - - if($rs == NULL) return -1; - - for($i=0; $iecccode,$eccPos); - $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); - $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); - - $dataPos += $dl; - $eccPos += $el; - $blockNo++; - } + $this->count = 0; + } + + //---------------------------------------------------------------------- + public function init(array $spec) + { + $dl = QRspec::rsDataCodes1($spec); + $el = QRspec::rsEccCodes1($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + $blockNo = 0; + $dataPos = 0; + $eccPos = 0; + for ($i = 0; $i < QRspec::rsBlockNum1($spec); $i++) { + $ecc = array_slice($this->ecccode, $eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc); + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + if (QRspec::rsBlockNum2($spec) == 0) { return 0; } - - //---------------------------------------------------------------------- - public function getCode() - { - $ret; - - if($this->count < $this->dataLength) { - $row = $this->count % $this->blocks; - $col = $this->count / $this->blocks; - if($col >= $this->rsblocks[0]->dataLength) { - $row += $this->b1; - } - $ret = $this->rsblocks[$row]->data[$col]; - } else if($this->count < $this->dataLength + $this->eccLength) { - $row = ($this->count - $this->dataLength) % $this->blocks; - $col = ($this->count - $this->dataLength) / $this->blocks; - $ret = $this->rsblocks[$row]->ecc[$col]; - } else { - return 0; - } - $this->count++; - - return $ret; + + $dl = QRspec::rsDataCodes2($spec); + $el = QRspec::rsEccCodes2($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + if ($rs == null) { + return -1; } + + for ($i = 0; $i < QRspec::rsBlockNum2($spec); $i++) { + $ecc = array_slice($this->ecccode, $eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + return 0; } - //########################################################################## - - class QRcode { - - public $version; - public $width; - public $data; - - //---------------------------------------------------------------------- - public function encodeMask(QRinput $input, $mask) - { - if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { - throw new Exception('wrong version'); - } - if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { - throw new Exception('wrong level'); - } + //---------------------------------------------------------------------- + public function getCode() + { + $ret; - $raw = new QRrawcode($input); - - QRtools::markTime('after_raw'); - - $version = $raw->version; - $width = QRspec::getWidth($version); - $frame = QRspec::newFrame($version); - - $filler = new FrameFiller($width, $frame); - if(is_null($filler)) { - return NULL; + if ($this->count < $this->dataLength) { + $row = $this->count % $this->blocks; + $col = $this->count / $this->blocks; + if ($col >= $this->rsblocks[0]->dataLength) { + $row += $this->b1; } + $ret = $this->rsblocks[$row]->data[$col]; + } else if ($this->count < $this->dataLength + $this->eccLength) { + $row = ($this->count - $this->dataLength) % $this->blocks; + $col = ($this->count - $this->dataLength) / $this->blocks; + $ret = $this->rsblocks[$row]->ecc[$col]; + } else { + return 0; + } + $this->count++; - // inteleaved data and ecc codes - for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) { - $code = $raw->getCode(); - $bit = 0x80; - for($j=0; $j<8; $j++) { - $addr = $filler->next(); - $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); - $bit = $bit >> 1; - } - } - - QRtools::markTime('after_filler'); - - unset($raw); - - // remainder bits - $j = QRspec::getRemainder($version); - for($i=0; $i<$j; $i++) { - $addr = $filler->next(); - $filler->setFrameAt($addr, 0x02); - } - - $frame = $filler->frame; - unset($filler); - - - // masking - $maskObj = new QRmask(); - if($mask < 0) { - - if (QR_FIND_BEST_MASK) { - $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); - } else { - $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel()); - } - } else { - $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); - } - - if($masked == NULL) { - return NULL; - } - - QRtools::markTime('after_mask'); - - $this->version = $version; - $this->width = $width; - $this->data = $masked; - - return $this; + return $ret; + } +} + +//########################################################################## + +class QRcode +{ + + public $version; + public $width; + public $data; + + //---------------------------------------------------------------------- + public function encodeMask(QRinput $input, $mask) + { + if ($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { + throw new Exception('wrong version'); } - - //---------------------------------------------------------------------- - public function encodeInput(QRinput $input) - { - return $this->encodeMask($input, -1); + if ($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { + throw new Exception('wrong level'); } - - //---------------------------------------------------------------------- - public function encodeString8bit($string, $version, $level) - { - if(string == NULL) { - throw new Exception('empty string!'); - return NULL; - } - $input = new QRinput($version, $level); - if($input == NULL) return NULL; + $raw = new QRrawcode($input); + + QRtools::markTime('after_raw'); - $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); - if($ret < 0) { - unset($input); - return NULL; + $version = $raw->version; + $width = QRspec::getWidth($version); + $frame = QRspec::newFrame($version); + + $filler = new FrameFiller($width, $frame); + if (is_null($filler)) { + return null; + } + + // inteleaved data and ecc codes + for ($i = 0; $i < $raw->dataLength + $raw->eccLength; $i++) { + $code = $raw->getCode(); + $bit = 0x80; + for ($j = 0; $j < 8; $j++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); + $bit = $bit >> 1; } - return $this->encodeInput($input); } - //---------------------------------------------------------------------- - public function encodeString($string, $version, $level, $hint, $casesensitive) - { + QRtools::markTime('after_filler'); - if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { - throw new Exception('bad hint'); - return NULL; - } + unset($raw); + + // remainder bits + $j = QRspec::getRemainder($version); + for ($i = 0; $i < $j; $i++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02); + } + + $frame = $filler->frame; + unset($filler); - $input = new QRinput($version, $level); - if($input == NULL) return NULL; + // masking + $maskObj = new QRmask(); + if ($mask < 0) { - $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); - if($ret < 0) { - return NULL; + if (QR_FIND_BEST_MASK) { + $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); + } else { + $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel()); } + } else { + $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); + } - return $this->encodeInput($input); + if ($masked == null) { + return null; } - - //---------------------------------------------------------------------- - public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false) - { - $enc = QRencode::factory($level, $size, $margin); - return $enc->encodePNG($text, $outfile, $saveandprint=false); + + QRtools::markTime('after_mask'); + + $this->version = $version; + $this->width = $width; + $this->data = $masked; + + return $this; + } + + //---------------------------------------------------------------------- + public function encodeInput(QRinput $input) + { + return $this->encodeMask($input, -1); + } + + //---------------------------------------------------------------------- + public function encodeString8bit($string, $version, $level) + { + if (string == null) { + throw new Exception('empty string!'); + return null; } - //---------------------------------------------------------------------- - public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) - { - $enc = QRencode::factory($level, $size, $margin); - return $enc->encode($text, $outfile); + $input = new QRinput($version, $level); + if ($input == null) { + return null; } - //---------------------------------------------------------------------- - public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) - { - $enc = QRencode::factory($level, $size, $margin); - return $enc->encodeRAW($text, $outfile); + $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); + if ($ret < 0) { + unset($input); + return null; } + return $this->encodeInput($input); } - - //########################################################################## - - class FrameFiller { - - public $width; - public $frame; - public $x; - public $y; - public $dir; - public $bit; - - //---------------------------------------------------------------------- - public function __construct($width, &$frame) - { - $this->width = $width; - $this->frame = $frame; - $this->x = $width - 1; - $this->y = $width - 1; - $this->dir = -1; - $this->bit = -1; + + //---------------------------------------------------------------------- + public function encodeString($string, $version, $level, $hint, $casesensitive) + { + + if ($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { + throw new Exception('bad hint'); + return null; } - - //---------------------------------------------------------------------- - public function setFrameAt($at, $val) - { - $this->frame[$at['y']][$at['x']] = chr($val); + + $input = new QRinput($version, $level); + if ($input == null) { + return null; } - - //---------------------------------------------------------------------- - public function getFrameAt($at) - { - return ord($this->frame[$at['y']][$at['x']]); + + $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); + if ($ret < 0) { + return null; } - - //---------------------------------------------------------------------- - public function next() - { - do { - - if($this->bit == -1) { - $this->bit = 0; - return array('x'=>$this->x, 'y'=>$this->y); - } - $x = $this->x; - $y = $this->y; - $w = $this->width; - - if($this->bit == 0) { - $x--; - $this->bit++; - } else { - $x++; - $y += $this->dir; - $this->bit--; - } + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint = false) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodePNG($text, $outfile, $saveandprint = false); + } + + //---------------------------------------------------------------------- + public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encode($text, $outfile); + } + + //---------------------------------------------------------------------- + public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodeRAW($text, $outfile); + } +} + +//########################################################################## + +class FrameFiller +{ + + public $width; + public $frame; + public $x; + public $y; + public $dir; + public $bit; + + //---------------------------------------------------------------------- + public function __construct($width, &$frame) + { + $this->width = $width; + $this->frame = $frame; + $this->x = $width - 1; + $this->y = $width - 1; + $this->dir = -1; + $this->bit = -1; + } + + //---------------------------------------------------------------------- + public function setFrameAt($at, $val) + { + $this->frame[$at['y']][$at['x']] = chr($val); + } - if($this->dir < 0) { - if($y < 0) { - $y = 0; - $x -= 2; - $this->dir = 1; - if($x == 6) { - $x--; - $y = 9; - } + //---------------------------------------------------------------------- + public function getFrameAt($at) + { + return ord($this->frame[$at['y']][$at['x']]); + } + + //---------------------------------------------------------------------- + public function next() + { + do { + + if ($this->bit == -1) { + $this->bit = 0; + return array('x' => $this->x, 'y' => $this->y); + } + + $x = $this->x; + $y = $this->y; + $w = $this->width; + + if ($this->bit == 0) { + $x--; + $this->bit++; + } else { + $x++; + $y += $this->dir; + $this->bit--; + } + + if ($this->dir < 0) { + if ($y < 0) { + $y = 0; + $x -= 2; + $this->dir = 1; + if ($x == 6) { + $x--; + $y = 9; } - } else { - if($y == $w) { - $y = $w - 1; - $x -= 2; - $this->dir = -1; - if($x == 6) { - $x--; - $y -= 8; - } + } + } else { + if ($y == $w) { + $y = $w - 1; + $x -= 2; + $this->dir = -1; + if ($x == 6) { + $x--; + $y -= 8; } } - if($x < 0 || $y < 0) return null; + } + if ($x < 0 || $y < 0) { + return null; + } + + $this->x = $x; + $this->y = $y; + + } while (ord($this->frame[$y][$x]) & 0x80); - $this->x = $x; - $this->y = $y; + return array('x' => $x, 'y' => $y); + } + +}; + +//########################################################################## + +class QRencode +{ + + public $casesensitive = true; + public $eightbit = false; + + public $version = 0; + public $size = 3; + public $margin = 4; + + public $structured = 0; // not supported yet + + public $level = QR_ECLEVEL_L; + public $hint = QR_MODE_8; + + //---------------------------------------------------------------------- + public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = new QRencode(); + $enc->size = $size; + $enc->margin = $margin; - } while(ord($this->frame[$y][$x]) & 0x80); - - return array('x'=>$x, 'y'=>$y); + switch ($level . '') { + case '0': + case '1': + case '2': + case '3': + $enc->level = $level; + break; + case 'l': + case 'L': + $enc->level = QR_ECLEVEL_L; + break; + case 'm': + case 'M': + $enc->level = QR_ECLEVEL_M; + break; + case 'q': + case 'Q': + $enc->level = QR_ECLEVEL_Q; + break; + case 'h': + case 'H': + $enc->level = QR_ECLEVEL_H; + break; } - - } ; - - //########################################################################## - - class QRencode { - - public $casesensitive = true; - public $eightbit = false; - - public $version = 0; - public $size = 3; - public $margin = 4; - - public $structured = 0; // not supported yet - - public $level = QR_ECLEVEL_L; - public $hint = QR_MODE_8; - - //---------------------------------------------------------------------- - public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) - { - $enc = new QRencode(); - $enc->size = $size; - $enc->margin = $margin; - - switch ($level.'') { - case '0': - case '1': - case '2': - case '3': - $enc->level = $level; - break; - case 'l': - case 'L': - $enc->level = QR_ECLEVEL_L; - break; - case 'm': - case 'M': - $enc->level = QR_ECLEVEL_M; - break; - case 'q': - case 'Q': - $enc->level = QR_ECLEVEL_Q; - break; - case 'h': - case 'H': - $enc->level = QR_ECLEVEL_H; - break; - } - - return $enc; + + return $enc; + } + + //---------------------------------------------------------------------- + public function encodeRAW($intext, $outfile = false) + { + $code = new QRcode(); + + if ($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); } - - //---------------------------------------------------------------------- - public function encodeRAW($intext, $outfile = false) - { - $code = new QRcode(); - - if($this->eightbit) { - $code->encodeString8bit($intext, $this->version, $this->level); - } else { - $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); - } - - return $code->data; + + return $code->data; + } + + //---------------------------------------------------------------------- + public function encode($intext, $outfile = false) + { + $code = new QRcode(); + + if ($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); } - //---------------------------------------------------------------------- - public function encode($intext, $outfile = false) - { - $code = new QRcode(); + QRtools::markTime('after_encode'); - if($this->eightbit) { - $code->encodeString8bit($intext, $this->version, $this->level); - } else { - $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); - } - - QRtools::markTime('after_encode'); - - if ($outfile!== false) { - file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); - } else { - return QRtools::binarize($code->data); - } + if ($outfile !== false) { + file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); + } else { + return QRtools::binarize($code->data); } - - //---------------------------------------------------------------------- - public function encodePNG($intext, $outfile = false,$saveandprint=false) - { - try { - - ob_start(); - $tab = $this->encode($intext); - $err = ob_get_contents(); - ob_end_clean(); - - if ($err != '') - QRtools::log($outfile, $err); - - $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin)); - - QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint); - - } catch (Exception $e) { - - QRtools::log($outfile, $e->getMessage()); - + } + + //---------------------------------------------------------------------- + public function encodePNG($intext, $outfile = false, $saveandprint = false) + { + try { + + ob_start(); + $tab = $this->encode($intext); + $err = ob_get_contents(); + ob_end_clean(); + + if ($err != '') { + QRtools::log($outfile, $err); } + + $maxSize = (int) (QR_PNG_MAXIMUM_SIZE / (count($tab) + 2 * $this->margin)); + + QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin, $saveandprint); + + } catch (Exception $e) { + + QRtools::log($outfile, $e->getMessage()); + } } +} diff --git a/include/qrcode/qrimage.php b/include/qrcode/qrimage.php index 46586375..c8c382f7 100755 --- a/include/qrcode/qrimage.php +++ b/include/qrcode/qrimage.php @@ -21,78 +21,79 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('QR_IMAGE', true); - - class QRimage { - - public static $black = array(255,255,255); - public static $white = array(0,0,0); - - //---------------------------------------------------------------------- - public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) - { - $image = self::image($frame, $pixelPerPoint, $outerFrame); - - if ($filename === false) { - Header("Content-type: image/png"); + +define('QR_IMAGE', true); + +class QRimage +{ + + public static $black = array(255, 255, 255); + public static $white = array(0, 0, 0); + + //---------------------------------------------------------------------- + public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4, $saveandprint = false) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/png"); + ImagePng($image); + } else { + if ($saveandprint === true) { + ImagePng($image, $filename); + header("Content-type: image/png"); ImagePng($image); } else { - if($saveandprint===TRUE){ - ImagePng($image, $filename); - header("Content-type: image/png"); - ImagePng($image); - }else{ - ImagePng($image, $filename); - } + ImagePng($image, $filename); } - - ImageDestroy($image); } - - //---------------------------------------------------------------------- - public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) - { - $image = self::image($frame, $pixelPerPoint, $outerFrame); - - if ($filename === false) { - Header("Content-type: image/jpeg"); - ImageJpeg($image, null, $q); - } else { - ImageJpeg($image, $filename, $q); - } - - ImageDestroy($image); + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/jpeg"); + ImageJpeg($image, null, $q); + } else { + ImageJpeg($image, $filename, $q); } - - //---------------------------------------------------------------------- - private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) - { - $h = count($frame); - $w = strlen($frame[0]); - - $imgW = $w + 2*$outerFrame; - $imgH = $h + 2*$outerFrame; - - $base_image =ImageCreate($imgW, $imgH); - - $col[0] = ImageColorAllocate($base_image,QRImage::$black[0],QRImage::$black[1],QRImage::$black[2]); - $col[1] = ImageColorAllocate($base_image,QRImage::$white[0],QRImage::$white[1],QRImage::$white[2]); - - imagefill($base_image, 0, 0, $col[0]); - - for($y=0; $y<$h; $y++) { - for($x=0; $x<$w; $x++) { - if ($frame[$y][$x] == '1') { - ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]); - } + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) + { + $h = count($frame); + $w = strlen($frame[0]); + + $imgW = $w + 2 * $outerFrame; + $imgH = $h + 2 * $outerFrame; + + $base_image = ImageCreate($imgW, $imgH); + + $col[0] = ImageColorAllocate($base_image, QRImage::$black[0], QRImage::$black[1], QRImage::$black[2]); + $col[1] = ImageColorAllocate($base_image, QRImage::$white[0], QRImage::$white[1], QRImage::$white[2]); + + imagefill($base_image, 0, 0, $col[0]); + + for ($y = 0; $y < $h; $y++) { + for ($x = 0; $x < $w; $x++) { + if ($frame[$y][$x] == '1') { + ImageSetPixel($base_image, $x + $outerFrame, $y + $outerFrame, $col[1]); } } - - $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); - ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); - ImageDestroy($base_image); - - return $target_image; } - } \ No newline at end of file + + $target_image = ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); + ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); + ImageDestroy($base_image); + + return $target_image; + } +} diff --git a/include/qrcode/qrinput.php b/include/qrcode/qrinput.php index c65f91a2..456a66f3 100755 --- a/include/qrcode/qrinput.php +++ b/include/qrcode/qrinput.php @@ -24,706 +24,734 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('STRUCTURE_HEADER_BITS', 20); - define('MAX_STRUCTURED_SYMBOLS', 16); - - class QRinputItem { - - public $mode; - public $size; - public $data; - public $bstream; - - public function __construct($mode, $size, $data, $bstream = null) - { - $setData = array_slice($data, 0, $size); - - if (count($setData) < $size) { - $setData = array_merge($setData, array_fill(0,$size-count($setData),0)); - } - - if(!QRinput::check($mode, $size, $setData)) { - throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData)); - return null; + +define('STRUCTURE_HEADER_BITS', 20); +define('MAX_STRUCTURED_SYMBOLS', 16); + +class QRinputItem +{ + + public $mode; + public $size; + public $data; + public $bstream; + + public function __construct($mode, $size, $data, $bstream = null) + { + $setData = array_slice($data, 0, $size); + + if (count($setData) < $size) { + $setData = array_merge($setData, array_fill(0, $size - count($setData), 0)); + } + + if (!QRinput::check($mode, $size, $setData)) { + throw new Exception('Error m:' . $mode . ',s:' . $size . ',d:' . join(',', $setData)); + return null; + } + + $this->mode = $mode; + $this->size = $size; + $this->data = $setData; + $this->bstream = $bstream; + } + + //---------------------------------------------------------------------- + public function encodeModeNum($version) + { + try { + + $words = (int) ($this->size / 3); + $bs = new QRbitstream(); + + $val = 0x1; + $bs->appendNum(4, $val); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); + + for ($i = 0; $i < $words; $i++) { + $val = (ord($this->data[$i * 3]) - ord('0')) * 100; + $val += (ord($this->data[$i * 3 + 1]) - ord('0')) * 10; + $val += (ord($this->data[$i * 3 + 2]) - ord('0')); + $bs->appendNum(10, $val); } - - $this->mode = $mode; - $this->size = $size; - $this->data = $setData; - $this->bstream = $bstream; - } - - //---------------------------------------------------------------------- - public function encodeModeNum($version) - { - try { - - $words = (int)($this->size / 3); - $bs = new QRbitstream(); - - $val = 0x1; + + if ($this->size - $words * 3 == 1) { + $val = ord($this->data[$words * 3]) - ord('0'); $bs->appendNum(4, $val); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); + } else if ($this->size - $words * 3 == 2) { + $val = (ord($this->data[$words * 3]) - ord('0')) * 10; + $val += (ord($this->data[$words * 3 + 1]) - ord('0')); + $bs->appendNum(7, $val); + } - for($i=0; $i<$words; $i++) { - $val = (ord($this->data[$i*3 ]) - ord('0')) * 100; - $val += (ord($this->data[$i*3+1]) - ord('0')) * 10; - $val += (ord($this->data[$i*3+2]) - ord('0')); - $bs->appendNum(10, $val); - } + $this->bstream = $bs; + return 0; - if($this->size - $words * 3 == 1) { - $val = ord($this->data[$words*3]) - ord('0'); - $bs->appendNum(4, $val); - } else if($this->size - $words * 3 == 2) { - $val = (ord($this->data[$words*3 ]) - ord('0')) * 10; - $val += (ord($this->data[$words*3+1]) - ord('0')); - $bs->appendNum(7, $val); - } + } catch (Exception $e) { + return -1; + } + } - $this->bstream = $bs; - return 0; - - } catch (Exception $e) { - return -1; + //---------------------------------------------------------------------- + public function encodeModeAn($version) + { + try { + $words = (int) ($this->size / 2); + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x02); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); + + for ($i = 0; $i < $words; $i++) { + $val = (int) QRinput::lookAnTable(ord($this->data[$i * 2])) * 45; + $val += (int) QRinput::lookAnTable(ord($this->data[$i * 2 + 1])); + + $bs->appendNum(11, $val); } - } - - //---------------------------------------------------------------------- - public function encodeModeAn($version) - { - try { - $words = (int)($this->size / 2); - $bs = new QRbitstream(); - - $bs->appendNum(4, 0x02); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); - - for($i=0; $i<$words; $i++) { - $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45; - $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1])); - - $bs->appendNum(11, $val); - } - if($this->size & 1) { - $val = QRinput::lookAnTable(ord($this->data[$words * 2])); - $bs->appendNum(6, $val); - } - - $this->bstream = $bs; - return 0; - - } catch (Exception $e) { - return -1; + if ($this->size & 1) { + $val = QRinput::lookAnTable(ord($this->data[$words * 2])); + $bs->appendNum(6, $val); } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; } - - //---------------------------------------------------------------------- - public function encodeMode8($version) - { - try { - $bs = new QRbitstream(); + } - $bs->appendNum(4, 0x4); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); + //---------------------------------------------------------------------- + public function encodeMode8($version) + { + try { + $bs = new QRbitstream(); - for($i=0; $i<$this->size; $i++) { - $bs->appendNum(8, ord($this->data[$i])); - } + $bs->appendNum(4, 0x4); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); - $this->bstream = $bs; - return 0; - - } catch (Exception $e) { - return -1; + for ($i = 0; $i < $this->size; $i++) { + $bs->appendNum(8, ord($this->data[$i])); } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; } - - //---------------------------------------------------------------------- - public function encodeModeKanji($version) - { - try { - - $bs = new QRbitrtream(); - - $bs->appendNum(4, 0x8); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2)); - - for($i=0; $i<$this->size; $i+=2) { - $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]); - if($val <= 0x9ffc) { - $val -= 0x8140; - } else { - $val -= 0xc140; - } - - $h = ($val >> 8) * 0xc0; - $val = ($val & 0xff) + $h; - - $bs->appendNum(13, $val); + } + + //---------------------------------------------------------------------- + public function encodeModeKanji($version) + { + try { + + $bs = new QRbitrtream(); + + $bs->appendNum(4, 0x8); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int) ($this->size / 2)); + + for ($i = 0; $i < $this->size; $i += 2) { + $val = (ord($this->data[$i]) << 8) | ord($this->data[$i + 1]); + if ($val <= 0x9ffc) { + $val -= 0x8140; + } else { + $val -= 0xc140; } - $this->bstream = $bs; - return 0; - - } catch (Exception $e) { - return -1; + $h = ($val >> 8) * 0xc0; + $val = ($val & 0xff) + $h; + + $bs->appendNum(13, $val); } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; } + } + + //---------------------------------------------------------------------- + public function encodeModeStructure() + { + try { + $bs = new QRbitstream(); - //---------------------------------------------------------------------- - public function encodeModeStructure() - { - try { - $bs = new QRbitstream(); - - $bs->appendNum(4, 0x03); - $bs->appendNum(4, ord($this->data[1]) - 1); - $bs->appendNum(4, ord($this->data[0]) - 1); - $bs->appendNum(8, ord($this->data[2])); + $bs->appendNum(4, 0x03); + $bs->appendNum(4, ord($this->data[1]) - 1); + $bs->appendNum(4, ord($this->data[0]) - 1); + $bs->appendNum(8, ord($this->data[2])); + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } - $this->bstream = $bs; + //---------------------------------------------------------------------- + public function estimateBitStreamSizeOfEntry($version) + { + $bits = 0; + + if ($version == 0) { + $version = 1; + } + + switch ($this->mode) { + case QR_MODE_NUM:$bits = QRinput::estimateBitsModeNum($this->size); + break; + case QR_MODE_AN:$bits = QRinput::estimateBitsModeAn($this->size); + break; + case QR_MODE_8:$bits = QRinput::estimateBitsMode8($this->size); + break; + case QR_MODE_KANJI:$bits = QRinput::estimateBitsModeKanji($this->size); + break; + case QR_MODE_STRUCTURE:return STRUCTURE_HEADER_BITS; + default: return 0; - - } catch (Exception $e) { - return -1; - } } - - //---------------------------------------------------------------------- - public function estimateBitStreamSizeOfEntry($version) - { - $bits = 0; - - if($version == 0) - $version = 1; - - switch($this->mode) { - case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break; - case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break; - case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break; - case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break; - case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; - default: - return 0; - } - $l = QRspec::lengthIndicator($this->mode, $version); - $m = 1 << $l; - $num = (int)(($this->size + $m - 1) / $m); - - $bits += $num * (4 + $l); - - return $bits; - } - - //---------------------------------------------------------------------- - public function encodeBitStream($version) - { - try { - - unset($this->bstream); - $words = QRspec::maximumWords($this->mode, $version); - - if($this->size > $words) { - - $st1 = new QRinputItem($this->mode, $words, $this->data); - $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); - - $st1->encodeBitStream($version); - $st2->encodeBitStream($version); - - $this->bstream = new QRbitstream(); - $this->bstream->append($st1->bstream); - $this->bstream->append($st2->bstream); - - unset($st1); - unset($st2); - - } else { - - $ret = 0; - - switch($this->mode) { - case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break; - case QR_MODE_AN: $ret = $this->encodeModeAn($version); break; - case QR_MODE_8: $ret = $this->encodeMode8($version); break; - case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break; - case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break; - - default: - break; - } - - if($ret < 0) - return -1; + $l = QRspec::lengthIndicator($this->mode, $version); + $m = 1 << $l; + $num = (int) (($this->size + $m - 1) / $m); + + $bits += $num * (4 + $l); + + return $bits; + } + + //---------------------------------------------------------------------- + public function encodeBitStream($version) + { + try { + + unset($this->bstream); + $words = QRspec::maximumWords($this->mode, $version); + + if ($this->size > $words) { + + $st1 = new QRinputItem($this->mode, $words, $this->data); + $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); + + $st1->encodeBitStream($version); + $st2->encodeBitStream($version); + + $this->bstream = new QRbitstream(); + $this->bstream->append($st1->bstream); + $this->bstream->append($st2->bstream); + + unset($st1); + unset($st2); + + } else { + + $ret = 0; + + switch ($this->mode) { + case QR_MODE_NUM:$ret = $this->encodeModeNum($version); + break; + case QR_MODE_AN:$ret = $this->encodeModeAn($version); + break; + case QR_MODE_8:$ret = $this->encodeMode8($version); + break; + case QR_MODE_KANJI:$ret = $this->encodeModeKanji($version); + break; + case QR_MODE_STRUCTURE:$ret = $this->encodeModeStructure(); + break; + + default: + break; + } + + if ($ret < 0) { + return -1; } - return $this->bstream->size(); - - } catch (Exception $e) { - return -1; } + + return $this->bstream->size(); + + } catch (Exception $e) { + return -1; } - }; - - //########################################################################## - - class QRinput { - - public $items; - - private $version; - private $level; - - //---------------------------------------------------------------------- - public function __construct($version = 0, $level = QR_ECLEVEL_L) - { - if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { - throw new Exception('Invalid version no'); - return NULL; - } - - $this->version = $version; - $this->level = $level; - } - - //---------------------------------------------------------------------- - public function getVersion() - { - return $this->version; - } - - //---------------------------------------------------------------------- - public function setVersion($version) - { - if($version < 0 || $version > QRSPEC_VERSION_MAX) { - throw new Exception('Invalid version no'); - return -1; - } + } +}; - $this->version = $version; +//########################################################################## - return 0; +class QRinput +{ + + public $items; + + private $version; + private $level; + + //---------------------------------------------------------------------- + public function __construct($version = 0, $level = QR_ECLEVEL_L) + { + if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { + throw new Exception('Invalid version no'); + return null; } - - //---------------------------------------------------------------------- - public function getErrorCorrectionLevel() - { - return $this->level; + + $this->version = $version; + $this->level = $level; + } + + //---------------------------------------------------------------------- + public function getVersion() + { + return $this->version; + } + + //---------------------------------------------------------------------- + public function setVersion($version) + { + if ($version < 0 || $version > QRSPEC_VERSION_MAX) { + throw new Exception('Invalid version no'); + return -1; } - //---------------------------------------------------------------------- - public function setErrorCorrectionLevel($level) - { - if($level > QR_ECLEVEL_H) { - throw new Exception('Invalid ECLEVEL'); - return -1; - } + $this->version = $version; - $this->level = $level; + return 0; + } - return 0; + //---------------------------------------------------------------------- + public function getErrorCorrectionLevel() + { + return $this->level; + } + + //---------------------------------------------------------------------- + public function setErrorCorrectionLevel($level) + { + if ($level > QR_ECLEVEL_H) { + throw new Exception('Invalid ECLEVEL'); + return -1; } - - //---------------------------------------------------------------------- - public function appendEntry(QRinputItem $entry) - { + + $this->level = $level; + + return 0; + } + + //---------------------------------------------------------------------- + public function appendEntry(QRinputItem $entry) + { + $this->items[] = $entry; + } + + //---------------------------------------------------------------------- + public function append($mode, $size, $data) + { + try { + $entry = new QRinputItem($mode, $size, $data); $this->items[] = $entry; + return 0; + } catch (Exception $e) { + return -1; } - - //---------------------------------------------------------------------- - public function append($mode, $size, $data) - { - try { - $entry = new QRinputItem($mode, $size, $data); - $this->items[] = $entry; - return 0; - } catch (Exception $e) { - return -1; - } + } + + //---------------------------------------------------------------------- + + public function insertStructuredAppendHeader($size, $index, $parity) + { + if ($size > MAX_STRUCTURED_SYMBOLS) { + throw new Exception('insertStructuredAppendHeader wrong size'); } - - //---------------------------------------------------------------------- - - public function insertStructuredAppendHeader($size, $index, $parity) - { - if( $size > MAX_STRUCTURED_SYMBOLS ) { - throw new Exception('insertStructuredAppendHeader wrong size'); - } - - if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) { - throw new Exception('insertStructuredAppendHeader wrong index'); - } - $buf = array($size, $index, $parity); - - try { - $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); - array_unshift($this->items, $entry); - return 0; - } catch (Exception $e) { - return -1; - } + if ($index <= 0 || $index > MAX_STRUCTURED_SYMBOLS) { + throw new Exception('insertStructuredAppendHeader wrong index'); } - //---------------------------------------------------------------------- - public function calcParity() - { - $parity = 0; - - foreach($this->items as $item) { - if($item->mode != QR_MODE_STRUCTURE) { - for($i=$item->size-1; $i>=0; $i--) { - $parity ^= $item->data[$i]; - } - } - } + $buf = array($size, $index, $parity); - return $parity; + try { + $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); + array_unshift($this->items, $entry); + return 0; + } catch (Exception $e) { + return -1; } - - //---------------------------------------------------------------------- - public static function checkModeNum($size, $data) - { - for($i=0; $i<$size; $i++) { - if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){ - return false; - } - } + } - return true; - } - - //---------------------------------------------------------------------- - public static function estimateBitsModeNum($size) - { - $w = (int)$size / 3; - $bits = $w * 10; - - switch($size - $w * 3) { - case 1: - $bits += 4; - break; - case 2: - $bits += 7; - break; - default: - break; - } + //---------------------------------------------------------------------- + public function calcParity() + { + $parity = 0; - return $bits; - } - - //---------------------------------------------------------------------- - public static $anTable = array( - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, - -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - ); - - //---------------------------------------------------------------------- - public static function lookAnTable($c) - { - return (($c > 127)?-1:self::$anTable[$c]); - } - - //---------------------------------------------------------------------- - public static function checkModeAn($size, $data) - { - for($i=0; $i<$size; $i++) { - if (self::lookAnTable(ord($data[$i])) == -1) { - return false; + foreach ($this->items as $item) { + if ($item->mode != QR_MODE_STRUCTURE) { + for ($i = $item->size - 1; $i >= 0; $i--) { + $parity ^= $item->data[$i]; } } + } - return true; - } - - //---------------------------------------------------------------------- - public static function estimateBitsModeAn($size) - { - $w = (int)($size / 2); - $bits = $w * 11; - - if($size & 1) { - $bits += 6; - } + return $parity; + } - return $bits; - } - - //---------------------------------------------------------------------- - public static function estimateBitsMode8($size) - { - return $size * 8; - } - - //---------------------------------------------------------------------- - public function estimateBitsModeKanji($size) - { - return (int)(($size / 2) * 13); - } - - //---------------------------------------------------------------------- - public static function checkModeKanji($size, $data) - { - if($size & 1) + //---------------------------------------------------------------------- + public static function checkModeNum($size, $data) + { + for ($i = 0; $i < $size; $i++) { + if ((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))) { return false; - - for($i=0; $i<$size; $i+=2) { - $val = (ord($data[$i]) << 8) | ord($data[$i+1]); - if( $val < 0x8140 - || ($val > 0x9ffc && $val < 0xe040) - || $val > 0xebbf) { - return false; - } } + } + + return true; + } - return true; + //---------------------------------------------------------------------- + public static function estimateBitsModeNum($size) + { + $w = (int) $size / 3; + $bits = $w * 10; + + switch ($size - $w * 3) { + case 1: + $bits += 4; + break; + case 2: + $bits += 7; + break; + default: + break; } - /*********************************************************************** - * Validation - **********************************************************************/ + return $bits; + } - public static function check($mode, $size, $data) - { - if($size <= 0) - return false; + //---------------------------------------------------------------------- + public static $anTable = array( + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + ); + + //---------------------------------------------------------------------- + public static function lookAnTable($c) + { + return (($c > 127) ? -1 : self::$anTable[$c]); + } - switch($mode) { - case QR_MODE_NUM: return self::checkModeNum($size, $data); break; - case QR_MODE_AN: return self::checkModeAn($size, $data); break; - case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break; - case QR_MODE_8: return true; break; - case QR_MODE_STRUCTURE: return true; break; - - default: - break; + //---------------------------------------------------------------------- + public static function checkModeAn($size, $data) + { + for ($i = 0; $i < $size; $i++) { + if (self::lookAnTable(ord($data[$i])) == -1) { + return false; } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeAn($size) + { + $w = (int) ($size / 2); + $bits = $w * 11; + + if ($size & 1) { + $bits += 6; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static function estimateBitsMode8($size) + { + return $size * 8; + } + //---------------------------------------------------------------------- + public function estimateBitsModeKanji($size) + { + return (int) (($size / 2) * 13); + } + + //---------------------------------------------------------------------- + public static function checkModeKanji($size, $data) + { + if ($size & 1) { return false; } - - - //---------------------------------------------------------------------- - public function estimateBitStreamSize($version) - { - $bits = 0; - foreach($this->items as $item) { - $bits += $item->estimateBitStreamSizeOfEntry($version); + for ($i = 0; $i < $size; $i += 2) { + $val = (ord($data[$i]) << 8) | ord($data[$i + 1]); + if ($val < 0x8140 + || ($val > 0x9ffc && $val < 0xe040) + || $val > 0xebbf) { + return false; } + } - return $bits; - } - - //---------------------------------------------------------------------- - public function estimateVersion() - { - $version = 0; - $prev = 0; - do { - $prev = $version; - $bits = $this->estimateBitStreamSize($prev); - $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); - if ($version < 0) { - return -1; - } - } while ($version > $prev); - - return $version; - } - - //---------------------------------------------------------------------- - public static function lengthOfCode($mode, $version, $bits) - { - $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); - switch($mode) { - case QR_MODE_NUM: - $chunks = (int)($payload / 10); - $remain = $payload - $chunks * 10; - $size = $chunks * 3; - if($remain >= 7) { - $size += 2; - } else if($remain >= 4) { - $size += 1; - } - break; - case QR_MODE_AN: - $chunks = (int)($payload / 11); - $remain = $payload - $chunks * 11; - $size = $chunks * 2; - if($remain >= 6) - $size++; - break; - case QR_MODE_8: - $size = (int)($payload / 8); - break; - case QR_MODE_KANJI: - $size = (int)(($payload / 13) * 2); - break; - case QR_MODE_STRUCTURE: - $size = (int)($payload / 8); - break; - default: - $size = 0; - break; - } - - $maxsize = QRspec::maximumWords($mode, $version); - if($size < 0) $size = 0; - if($size > $maxsize) $size = $maxsize; - - return $size; - } - - //---------------------------------------------------------------------- - public function createBitStream() - { - $total = 0; - - foreach($this->items as $item) { - $bits = $item->encodeBitStream($this->version); - - if($bits < 0) - return -1; - - $total += $bits; - } + return true; + } + + /*********************************************************************** + * Validation + **********************************************************************/ - return $total; + public static function check($mode, $size, $data) + { + if ($size <= 0) { + return false; } - - //---------------------------------------------------------------------- - public function convertData() - { - $ver = $this->estimateVersion(); - if($ver > $this->getVersion()) { - $this->setVersion($ver); + + switch ($mode) { + case QR_MODE_NUM:return self::checkModeNum($size, $data); + break; + case QR_MODE_AN:return self::checkModeAn($size, $data); + break; + case QR_MODE_KANJI:return self::checkModeKanji($size, $data); + break; + case QR_MODE_8:return true; + break; + case QR_MODE_STRUCTURE:return true; + break; + + default: + break; + } + + return false; + } + + //---------------------------------------------------------------------- + public function estimateBitStreamSize($version) + { + $bits = 0; + + foreach ($this->items as $item) { + $bits += $item->estimateBitStreamSizeOfEntry($version); + } + + return $bits; + } + + //---------------------------------------------------------------------- + public function estimateVersion() + { + $version = 0; + $prev = 0; + do { + $prev = $version; + $bits = $this->estimateBitStreamSize($prev); + $version = QRspec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); + if ($version < 0) { + return -1; } + } while ($version > $prev); - for(;;) { - $bits = $this->createBitStream(); - - if($bits < 0) - return -1; - - $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); - if($ver < 0) { - throw new Exception('WRONG VERSION'); - return -1; - } else if($ver > $this->getVersion()) { - $this->setVersion($ver); - } else { - break; + return $version; + } + + //---------------------------------------------------------------------- + public static function lengthOfCode($mode, $version, $bits) + { + $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); + switch ($mode) { + case QR_MODE_NUM: + $chunks = (int) ($payload / 10); + $remain = $payload - $chunks * 10; + $size = $chunks * 3; + if ($remain >= 7) { + $size += 2; + } else if ($remain >= 4) { + $size += 1; + } + break; + case QR_MODE_AN: + $chunks = (int) ($payload / 11); + $remain = $payload - $chunks * 11; + $size = $chunks * 2; + if ($remain >= 6) { + $size++; } + + break; + case QR_MODE_8: + $size = (int) ($payload / 8); + break; + case QR_MODE_KANJI: + $size = (int) (($payload / 13) * 2); + break; + case QR_MODE_STRUCTURE: + $size = (int) ($payload / 8); + break; + default: + $size = 0; + break; + } + + $maxsize = QRspec::maximumWords($mode, $version); + if ($size < 0) { + $size = 0; + } + + if ($size > $maxsize) { + $size = $maxsize; + } + + return $size; + } + + //---------------------------------------------------------------------- + public function createBitStream() + { + $total = 0; + + foreach ($this->items as $item) { + $bits = $item->encodeBitStream($this->version); + + if ($bits < 0) { + return -1; } - return 0; + $total += $bits; } - - //---------------------------------------------------------------------- - public function appendPaddingBit(&$bstream) - { - $bits = $bstream->size(); - $maxwords = QRspec::getDataLength($this->version, $this->level); - $maxbits = $maxwords * 8; - if ($maxbits == $bits) { - return 0; + return $total; + } + + //---------------------------------------------------------------------- + public function convertData() + { + $ver = $this->estimateVersion(); + if ($ver > $this->getVersion()) { + $this->setVersion($ver); + } + + for (;;) { + $bits = $this->createBitStream(); + + if ($bits < 0) { + return -1; } - if ($maxbits - $bits < 5) { - return $bstream->appendNum($maxbits - $bits, 0); + $ver = QRspec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); + if ($ver < 0) { + throw new Exception('WRONG VERSION'); + return -1; + } else if ($ver > $this->getVersion()) { + $this->setVersion($ver); + } else { + break; } + } - $bits += 4; - $words = (int)(($bits + 7) / 8); + return 0; + } - $padding = new QRbitstream(); - $ret = $padding->appendNum($words * 8 - $bits + 4, 0); - - if($ret < 0) - return $ret; + //---------------------------------------------------------------------- + public function appendPaddingBit(&$bstream) + { + $bits = $bstream->size(); + $maxwords = QRspec::getDataLength($this->version, $this->level); + $maxbits = $maxwords * 8; - $padlen = $maxwords - $words; - - if($padlen > 0) { - - $padbuf = array(); - for($i=0; $i<$padlen; $i++) { - $padbuf[$i] = ($i&1)?0x11:0xec; - } - - $ret = $padding->appendBytes($padlen, $padbuf); - - if($ret < 0) - return $ret; - - } + if ($maxbits == $bits) { + return 0; + } - $ret = $bstream->append($padding); - + if ($maxbits - $bits < 5) { + return $bstream->appendNum($maxbits - $bits, 0); + } + + $bits += 4; + $words = (int) (($bits + 7) / 8); + + $padding = new QRbitstream(); + $ret = $padding->appendNum($words * 8 - $bits + 4, 0); + + if ($ret < 0) { return $ret; } - //---------------------------------------------------------------------- - public function mergeBitStream() - { - if($this->convertData() < 0) { - return null; + $padlen = $maxwords - $words; + + if ($padlen > 0) { + + $padbuf = array(); + for ($i = 0; $i < $padlen; $i++) { + $padbuf[$i] = ($i & 1) ? 0x11 : 0xec; } - $bstream = new QRbitstream(); - - foreach($this->items as $item) { - $ret = $bstream->append($item->bstream); - if($ret < 0) { - return null; - } + $ret = $padding->appendBytes($padlen, $padbuf); + + if ($ret < 0) { + return $ret; } - return $bstream; } - //---------------------------------------------------------------------- - public function getBitStream() - { + $ret = $bstream->append($padding); - $bstream = $this->mergeBitStream(); - - if($bstream == null) { - return null; - } - - $ret = $this->appendPaddingBit($bstream); - if($ret < 0) { - return null; - } + return $ret; + } - return $bstream; + //---------------------------------------------------------------------- + public function mergeBitStream() + { + if ($this->convertData() < 0) { + return null; } - - //---------------------------------------------------------------------- - public function getByteStream() - { - $bstream = $this->getBitStream(); - if($bstream == null) { + + $bstream = new QRbitstream(); + + foreach ($this->items as $item) { + $ret = $bstream->append($item->bstream); + if ($ret < 0) { return null; } - - return $bstream->toByte(); } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getBitStream() + { + + $bstream = $this->mergeBitStream(); + + if ($bstream == null) { + return null; + } + + $ret = $this->appendPaddingBit($bstream); + if ($ret < 0) { + return null; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getByteStream() + { + $bstream = $this->getBitStream(); + if ($bstream == null) { + return null; + } + + return $bstream->toByte(); } - - - \ No newline at end of file +} diff --git a/include/qrcode/qrlib.php b/include/qrcode/qrlib.php index 43059b9d..f852db48 100755 --- a/include/qrcode/qrlib.php +++ b/include/qrcode/qrlib.php @@ -24,20 +24,19 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - $QR_BASEDIR = dirname(__FILE__).DIRECTORY_SEPARATOR; - - // Required libs - - include $QR_BASEDIR."qrconst.php"; - include $QR_BASEDIR."qrconfig.php"; - include $QR_BASEDIR."qrtools.php"; - include $QR_BASEDIR."qrspec.php"; - include $QR_BASEDIR."qrimage.php"; - include $QR_BASEDIR."qrinput.php"; - include $QR_BASEDIR."qrbitstream.php"; - include $QR_BASEDIR."qrsplit.php"; - include $QR_BASEDIR."qrrscode.php"; - include $QR_BASEDIR."qrmask.php"; - include $QR_BASEDIR."qrencode.php"; +$QR_BASEDIR = dirname(__FILE__) . DIRECTORY_SEPARATOR; + +// Required libs + +include $QR_BASEDIR . "qrconst.php"; +include $QR_BASEDIR . "qrconfig.php"; +include $QR_BASEDIR . "qrtools.php"; +include $QR_BASEDIR . "qrspec.php"; +include $QR_BASEDIR . "qrimage.php"; +include $QR_BASEDIR . "qrinput.php"; +include $QR_BASEDIR . "qrbitstream.php"; +include $QR_BASEDIR . "qrsplit.php"; +include $QR_BASEDIR . "qrrscode.php"; +include $QR_BASEDIR . "qrmask.php"; +include $QR_BASEDIR . "qrencode.php"; diff --git a/include/qrcode/qrmask.php b/include/qrcode/qrmask.php index 2d388e0e..77bcf108 100755 --- a/include/qrcode/qrmask.php +++ b/include/qrcode/qrmask.php @@ -24,305 +24,319 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('N1', 3); - define('N2', 3); - define('N3', 40); - define('N4', 10); - - class QRmask { - - public $runLength = array(); - - //---------------------------------------------------------------------- - public function __construct() - { - $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); + +define('N1', 3); +define('N2', 3); +define('N3', 40); +define('N4', 10); + +class QRmask +{ + + public $runLength = array(); + + //---------------------------------------------------------------------- + public function __construct() + { + $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); + } + + //---------------------------------------------------------------------- + public function writeFormatInformation($width, &$frame, $mask, $level) + { + $blacks = 0; + $format = QRspec::getFormatInfo($mask, $level); + + for ($i = 0; $i < 8; $i++) { + if ($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; + } + + $frame[8][$width - 1 - $i] = chr($v); + if ($i < 6) { + $frame[$i][8] = chr($v); + } else { + $frame[$i + 1][8] = chr($v); + } + $format = $format >> 1; } - - //---------------------------------------------------------------------- - public function writeFormatInformation($width, &$frame, $mask, $level) - { - $blacks = 0; - $format = QRspec::getFormatInfo($mask, $level); - for($i=0; $i<8; $i++) { - if($format & 1) { - $blacks += 2; - $v = 0x85; - } else { - $v = 0x84; - } - - $frame[8][$width - 1 - $i] = chr($v); - if($i < 6) { - $frame[$i][8] = chr($v); - } else { - $frame[$i + 1][8] = chr($v); - } - $format = $format >> 1; + for ($i = 0; $i < 7; $i++) { + if ($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; } - - for($i=0; $i<7; $i++) { - if($format & 1) { - $blacks += 2; - $v = 0x85; - } else { - $v = 0x84; - } - - $frame[$width - 7 + $i][8] = chr($v); - if($i == 0) { - $frame[8][7] = chr($v); - } else { - $frame[8][6 - $i] = chr($v); - } - - $format = $format >> 1; + + $frame[$width - 7 + $i][8] = chr($v); + if ($i == 0) { + $frame[8][7] = chr($v); + } else { + $frame[8][6 - $i] = chr($v); } - return $blacks; + $format = $format >> 1; } - - //---------------------------------------------------------------------- - public function mask0($x, $y) { return ($x+$y)&1; } - public function mask1($x, $y) { return ($y&1); } - public function mask2($x, $y) { return ($x%3); } - public function mask3($x, $y) { return ($x+$y)%3; } - public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; } - public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; } - public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; } - public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; } - - //---------------------------------------------------------------------- - private function generateMaskNo($maskNo, $width, $frame) - { - $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); - - for($y=0; $y<$width; $y++) { - for($x=0; $x<$width; $x++) { - if(ord($frame[$y][$x]) & 0x80) { - $bitMask[$y][$x] = 0; - } else { - $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y); - $bitMask[$y][$x] = ($maskFunc == 0)?1:0; - } - + + return $blacks; + } + + //---------------------------------------------------------------------- + public function mask0($x, $y) + {return ($x + $y) & 1;} + public function mask1($x, $y) + {return ($y & 1);} + public function mask2($x, $y) + {return ($x % 3);} + public function mask3($x, $y) + {return ($x + $y) % 3;} + public function mask4($x, $y) + {return (((int) ($y / 2)) + ((int) ($x / 3))) & 1;} + public function mask5($x, $y) + {return (($x * $y) & 1) + ($x * $y) % 3;} + public function mask6($x, $y) + {return ((($x * $y) & 1) + ($x * $y) % 3) & 1;} + public function mask7($x, $y) + {return ((($x * $y) % 3) + (($x + $y) & 1)) & 1;} + + //---------------------------------------------------------------------- + private function generateMaskNo($maskNo, $width, $frame) + { + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { + if (ord($frame[$y][$x]) & 0x80) { + $bitMask[$y][$x] = 0; + } else { + $maskFunc = call_user_func(array($this, 'mask' . $maskNo), $x, $y); + $bitMask[$y][$x] = ($maskFunc == 0) ? 1 : 0; } + } - - return $bitMask; } - - //---------------------------------------------------------------------- - public static function serial($bitFrame) - { - $codeArr = array(); - - foreach ($bitFrame as $line) - $codeArr[] = join('', $line); - - return gzcompress(join("\n", $codeArr), 9); + + return $bitMask; + } + + //---------------------------------------------------------------------- + public static function serial($bitFrame) + { + $codeArr = array(); + + foreach ($bitFrame as $line) { + $codeArr[] = join('', $line); } - - //---------------------------------------------------------------------- - public static function unserial($code) - { - $codeArr = array(); - - $codeLines = explode("\n", gzuncompress($code)); - foreach ($codeLines as $line) - $codeArr[] = str_split($line); - - return $codeArr; + + return gzcompress(join("\n", $codeArr), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + $codeArr = array(); + + $codeLines = explode("\n", gzuncompress($code)); + foreach ($codeLines as $line) { + $codeArr[] = str_split($line); } - - //---------------------------------------------------------------------- - public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) - { - $b = 0; - $bitMask = array(); - - $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat'; - - if (QR_CACHEABLE) { - if (file_exists($fileName)) { - $bitMask = self::unserial(file_get_contents($fileName)); - } else { - $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); - if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) - mkdir(QR_CACHE_DIR.'mask_'.$maskNo); - file_put_contents($fileName, self::serial($bitMask)); - } + + return $codeArr; + } + + //---------------------------------------------------------------------- + public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) + { + $b = 0; + $bitMask = array(); + + $fileName = QR_CACHE_DIR . 'mask_' . $maskNo . DIRECTORY_SEPARATOR . 'mask_' . $width . '_' . $maskNo . '.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + $bitMask = self::unserial(file_get_contents($fileName)); } else { $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + if (!file_exists(QR_CACHE_DIR . 'mask_' . $maskNo)) { + mkdir(QR_CACHE_DIR . 'mask_' . $maskNo); + } + + file_put_contents($fileName, self::serial($bitMask)); } + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + } - if ($maskGenOnly) - return; - - $d = $s; + if ($maskGenOnly) { + return; + } - for($y=0; $y<$width; $y++) { - for($x=0; $x<$width; $x++) { - if($bitMask[$y][$x] == 1) { - $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]); - } - $b += (int)(ord($d[$y][$x]) & 1); + $d = $s; + + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { + if ($bitMask[$y][$x] == 1) { + $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int) $bitMask[$y][$x]); } + $b += (int) (ord($d[$y][$x]) & 1); } - - return $b; } - - //---------------------------------------------------------------------- - public function makeMask($width, $frame, $maskNo, $level) - { - $masked = array_fill(0, $width, str_repeat("\0", $width)); - $this->makeMaskNo($maskNo, $width, $frame, $masked); - $this->writeFormatInformation($width, $masked, $maskNo, $level); - - return $masked; - } - - //---------------------------------------------------------------------- - public function calcN1N3($length) - { - $demerit = 0; - for($i=0; $i<$length; $i++) { - - if($this->runLength[$i] >= 5) { - $demerit += (N1 + ($this->runLength[$i] - 5)); - } - if($i & 1) { - if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) { - $fact = (int)($this->runLength[$i] / 3); - if(($this->runLength[$i-2] == $fact) && - ($this->runLength[$i-1] == $fact) && - ($this->runLength[$i+1] == $fact) && - ($this->runLength[$i+2] == $fact)) { - if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) { - $demerit += N3; - } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) { - $demerit += N3; - } + return $b; + } + + //---------------------------------------------------------------------- + public function makeMask($width, $frame, $maskNo, $level) + { + $masked = array_fill(0, $width, str_repeat("\0", $width)); + $this->makeMaskNo($maskNo, $width, $frame, $masked); + $this->writeFormatInformation($width, $masked, $maskNo, $level); + + return $masked; + } + + //---------------------------------------------------------------------- + public function calcN1N3($length) + { + $demerit = 0; + + for ($i = 0; $i < $length; $i++) { + + if ($this->runLength[$i] >= 5) { + $demerit += (N1 + ($this->runLength[$i] - 5)); + } + if ($i & 1) { + if (($i >= 3) && ($i < ($length - 2)) && ($this->runLength[$i] % 3 == 0)) { + $fact = (int) ($this->runLength[$i] / 3); + if (($this->runLength[$i - 2] == $fact) && + ($this->runLength[$i - 1] == $fact) && + ($this->runLength[$i + 1] == $fact) && + ($this->runLength[$i + 2] == $fact)) { + if (($this->runLength[$i - 3] < 0) || ($this->runLength[$i - 3] >= (4 * $fact))) { + $demerit += N3; + } else if ((($i + 3) >= $length) || ($this->runLength[$i + 3] >= (4 * $fact))) { + $demerit += N3; } } } } - return $demerit; } - - //---------------------------------------------------------------------- - public function evaluateSymbol($width, $frame) - { + return $demerit; + } + + //---------------------------------------------------------------------- + public function evaluateSymbol($width, $frame) + { + $head = 0; + $demerit = 0; + + for ($y = 0; $y < $width; $y++) { $head = 0; - $demerit = 0; + $this->runLength[0] = 1; - for($y=0; $y<$width; $y++) { - $head = 0; - $this->runLength[0] = 1; - - $frameY = $frame[$y]; - - if ($y>0) - $frameYM = $frame[$y-1]; - - for($x=0; $x<$width; $x++) { - if(($x > 0) && ($y > 0)) { - $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]); - $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]); - - if(($b22 | ($w22 ^ 1))&1) { - $demerit += N2; - } + $frameY = $frame[$y]; + + if ($y > 0) { + $frameYM = $frame[$y - 1]; + } + + for ($x = 0; $x < $width; $x++) { + if (($x > 0) && ($y > 0)) { + $b22 = ord($frameY[$x]) & ord($frameY[$x - 1]) & ord($frameYM[$x]) & ord($frameYM[$x - 1]); + $w22 = ord($frameY[$x]) | ord($frameY[$x - 1]) | ord($frameYM[$x]) | ord($frameYM[$x - 1]); + + if (($b22 | ($w22 ^ 1)) & 1) { + $demerit += N2; } - if(($x == 0) && (ord($frameY[$x]) & 1)) { - $this->runLength[0] = -1; - $head = 1; + } + if (($x == 0) && (ord($frameY[$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if ($x > 0) { + if ((ord($frameY[$x]) ^ ord($frameY[$x - 1])) & 1) { + $head++; $this->runLength[$head] = 1; - } else if($x > 0) { - if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) { - $head++; - $this->runLength[$head] = 1; - } else { - $this->runLength[$head]++; - } + } else { + $this->runLength[$head]++; } } - - $demerit += $this->calcN1N3($head+1); } - for($x=0; $x<$width; $x++) { - $head = 0; - $this->runLength[0] = 1; - - for($y=0; $y<$width; $y++) { - if($y == 0 && (ord($frame[$y][$x]) & 1)) { - $this->runLength[0] = -1; - $head = 1; + $demerit += $this->calcN1N3($head + 1); + } + + for ($x = 0; $x < $width; $x++) { + $head = 0; + $this->runLength[0] = 1; + + for ($y = 0; $y < $width; $y++) { + if ($y == 0 && (ord($frame[$y][$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if ($y > 0) { + if ((ord($frame[$y][$x]) ^ ord($frame[$y - 1][$x])) & 1) { + $head++; $this->runLength[$head] = 1; - } else if($y > 0) { - if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) { - $head++; - $this->runLength[$head] = 1; - } else { - $this->runLength[$head]++; - } + } else { + $this->runLength[$head]++; } } - - $demerit += $this->calcN1N3($head+1); } - return $demerit; + $demerit += $this->calcN1N3($head + 1); } - - - //---------------------------------------------------------------------- - public function mask($width, $frame, $level) - { - $minDemerit = PHP_INT_MAX; - $bestMaskNum = 0; - $bestMask = array(); - - $checked_masks = array(0,1,2,3,4,5,6,7); - - if (QR_FIND_FROM_RANDOM !== false) { - - $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9); - for ($i = 0; $i < $howManuOut; $i++) { - $remPos = rand (0, count($checked_masks)-1); - unset($checked_masks[$remPos]); - $checked_masks = array_values($checked_masks); - } - + + return $demerit; + } + + //---------------------------------------------------------------------- + public function mask($width, $frame, $level) + { + $minDemerit = PHP_INT_MAX; + $bestMaskNum = 0; + $bestMask = array(); + + $checked_masks = array(0, 1, 2, 3, 4, 5, 6, 7); + + if (QR_FIND_FROM_RANDOM !== false) { + + $howManuOut = 8 - (QR_FIND_FROM_RANDOM % 9); + for ($i = 0; $i < $howManuOut; $i++) { + $remPos = rand(0, count($checked_masks) - 1); + unset($checked_masks[$remPos]); + $checked_masks = array_values($checked_masks); } - - $bestMask = $frame; - - foreach($checked_masks as $i) { - $mask = array_fill(0, $width, str_repeat("\0", $width)); - - $demerit = 0; - $blacks = 0; - $blacks = $this->makeMaskNo($i, $width, $frame, $mask); - $blacks += $this->writeFormatInformation($width, $mask, $i, $level); - $blacks = (int)(100 * $blacks / ($width * $width)); - $demerit = (int)((int)(abs($blacks - 50) / 5) * N4); - $demerit += $this->evaluateSymbol($width, $mask); - - if($demerit < $minDemerit) { - $minDemerit = $demerit; - $bestMask = $mask; - $bestMaskNum = $i; - } + + } + + $bestMask = $frame; + + foreach ($checked_masks as $i) { + $mask = array_fill(0, $width, str_repeat("\0", $width)); + + $demerit = 0; + $blacks = 0; + $blacks = $this->makeMaskNo($i, $width, $frame, $mask); + $blacks += $this->writeFormatInformation($width, $mask, $i, $level); + $blacks = (int) (100 * $blacks / ($width * $width)); + $demerit = (int) ((int) (abs($blacks - 50) / 5) * N4); + $demerit += $this->evaluateSymbol($width, $mask); + + if ($demerit < $minDemerit) { + $minDemerit = $demerit; + $bestMask = $mask; + $bestMaskNum = $i; } - - return $bestMask; } - - //---------------------------------------------------------------------- + + return $bestMask; } + + //---------------------------------------------------------------------- +} diff --git a/include/qrcode/qrrscode.php b/include/qrcode/qrrscode.php index d7a97d9a..c9c63dd4 100755 --- a/include/qrcode/qrrscode.php +++ b/include/qrcode/qrrscode.php @@ -3,7 +3,7 @@ * PHP QR Code encoder * * Reed-Solomon error correction support - * + * * Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q * (libfec is released under the GNU Lesser General Public License.) * @@ -27,184 +27,219 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRrsItem { - - public $mm; // Bits per symbol - public $nn; // Symbols per block (= (1<= $this->nn) { - $x -= $this->nn; - $x = ($x >> $this->mm) + ($x & $this->nn); + +class QRrsItem +{ + + public $mm; // Bits per symbol + public $nn; // Symbols per block (= (1<= $this->nn) { + $x -= $this->nn; + $x = ($x >> $this->mm) + ($x & $this->nn); + } + + return $x; + } + + //---------------------------------------------------------------------- + public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + // Common code for intializing a Reed-Solomon control block (char or int symbols) + // Copyright 2004 Phil Karn, KA9Q + // May be used under the terms of the GNU Lesser General Public License (LGPL) + + $rs = null; + + // Check parameter ranges + if ($symsize < 0 || $symsize > 8) { + return $rs; + } + + if ($fcr < 0 || $fcr >= (1 << $symsize)) { + return $rs; + } + + if ($prim <= 0 || $prim >= (1 << $symsize)) { + return $rs; + } + + if ($nroots < 0 || $nroots >= (1 << $symsize)) { + return $rs; + } + // Can't have more roots than symbol values! + if ($pad < 0 || $pad >= ((1 << $symsize) - 1 - $nroots)) { + return $rs; + } + // Too much padding + + $rs = new QRrsItem(); + $rs->mm = $symsize; + $rs->nn = (1 << $symsize) - 1; + $rs->pad = $pad; + + $rs->alpha_to = array_fill(0, $rs->nn + 1, 0); + $rs->index_of = array_fill(0, $rs->nn + 1, 0); + + // PHP style macro replacement ;) + $NN = &$rs->nn; + $A0 = &$NN; + + // Generate Galois field lookup tables + $rs->index_of[0] = $A0; // log(zero) = -inf + $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 + $sr = 1; + + for ($i = 0; $i < $rs->nn; $i++) { + $rs->index_of[$sr] = $i; + $rs->alpha_to[$i] = $sr; + $sr <<= 1; + if ($sr & (1 << $symsize)) { + $sr ^= $gfpoly; } - - return $x; + $sr &= $rs->nn; } - - //---------------------------------------------------------------------- - public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) - { - // Common code for intializing a Reed-Solomon control block (char or int symbols) - // Copyright 2004 Phil Karn, KA9Q - // May be used under the terms of the GNU Lesser General Public License (LGPL) + if ($sr != 1) { + // field generator polynomial is not primitive! $rs = null; - - // Check parameter ranges - if($symsize < 0 || $symsize > 8) return $rs; - if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs; - if($prim <= 0 || $prim >= (1<<$symsize)) return $rs; - if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values! - if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding - - $rs = new QRrsItem(); - $rs->mm = $symsize; - $rs->nn = (1<<$symsize)-1; - $rs->pad = $pad; - - $rs->alpha_to = array_fill(0, $rs->nn+1, 0); - $rs->index_of = array_fill(0, $rs->nn+1, 0); - - // PHP style macro replacement ;) - $NN =& $rs->nn; - $A0 =& $NN; - - // Generate Galois field lookup tables - $rs->index_of[0] = $A0; // log(zero) = -inf - $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 - $sr = 1; - - for($i=0; $i<$rs->nn; $i++) { - $rs->index_of[$sr] = $i; - $rs->alpha_to[$i] = $sr; - $sr <<= 1; - if($sr & (1<<$symsize)) { - $sr ^= $gfpoly; - } - $sr &= $rs->nn; - } - - if($sr != 1){ - // field generator polynomial is not primitive! - $rs = NULL; - return $rs; - } + return $rs; + } + + /* Form RS code generator polynomial from its roots */ + $rs->genpoly = array_fill(0, $nroots + 1, 0); + + $rs->fcr = $fcr; + $rs->prim = $prim; + $rs->nroots = $nroots; + $rs->gfpoly = $gfpoly; - /* Form RS code generator polynomial from its roots */ - $rs->genpoly = array_fill(0, $nroots+1, 0); - - $rs->fcr = $fcr; - $rs->prim = $prim; - $rs->nroots = $nroots; - $rs->gfpoly = $gfpoly; - - /* Find prim-th root of 1, used in decoding */ - for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn) - ; // intentional empty-body loop! - - $rs->iprim = (int)($iprim / $prim); - $rs->genpoly[0] = 1; - - for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) { - $rs->genpoly[$i+1] = 1; - - // Multiply rs->genpoly[] by @**(root + x) - for ($j = $i; $j > 0; $j--) { - if ($rs->genpoly[$j] != 0) { - $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; - } else { - $rs->genpoly[$j] = $rs->genpoly[$j-1]; - } + /* Find prim-th root of 1, used in decoding */ + for ($iprim = 1; ($iprim % $prim) != 0; $iprim += $rs->nn) + ; // intentional empty-body loop! + + $rs->iprim = (int) ($iprim / $prim); + $rs->genpoly[0] = 1; + + for ($i = 0, $root = $fcr * $prim; $i < $nroots; $i++, $root += $prim) { + $rs->genpoly[$i + 1] = 1; + + // Multiply rs->genpoly[] by @**(root + x) + for ($j = $i; $j > 0; $j--) { + if ($rs->genpoly[$j] != 0) { + $rs->genpoly[$j] = $rs->genpoly[$j - 1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; + } else { + $rs->genpoly[$j] = $rs->genpoly[$j - 1]; } - // rs->genpoly[0] can never be zero - $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; } - - // convert rs->genpoly[] to index form for quicker encoding - for ($i = 0; $i <= $nroots; $i++) - $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; + // rs->genpoly[0] can never be zero + $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; + } - return $rs; + // convert rs->genpoly[] to index form for quicker encoding + for ($i = 0; $i <= $nroots; $i++) { + $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; } - - //---------------------------------------------------------------------- - public function encode_rs_char($data, &$parity) - { - $MM =& $this->mm; - $NN =& $this->nn; - $ALPHA_TO =& $this->alpha_to; - $INDEX_OF =& $this->index_of; - $GENPOLY =& $this->genpoly; - $NROOTS =& $this->nroots; - $FCR =& $this->fcr; - $PRIM =& $this->prim; - $IPRIM =& $this->iprim; - $PAD =& $this->pad; - $A0 =& $NN; - - $parity = array_fill(0, $NROOTS, 0); - - for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) { - - $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; - if($feedback != $A0) { - // feedback term is non-zero - - // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must - // always be for the polynomials constructed by init_rs() - $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); - - for($j=1;$j<$NROOTS;$j++) { - $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])]; - } - } - - // Shift - array_shift($parity); - if($feedback != $A0) { - array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); - } else { - array_push($parity, 0); + + return $rs; + } + + //---------------------------------------------------------------------- + public function encode_rs_char($data, &$parity) + { + $MM = &$this->mm; + $NN = &$this->nn; + $ALPHA_TO = &$this->alpha_to; + $INDEX_OF = &$this->index_of; + $GENPOLY = &$this->genpoly; + $NROOTS = &$this->nroots; + $FCR = &$this->fcr; + $PRIM = &$this->prim; + $IPRIM = &$this->iprim; + $PAD = &$this->pad; + $A0 = &$NN; + + $parity = array_fill(0, $NROOTS, 0); + + for ($i = 0; $i < ($NN - $NROOTS - $PAD); $i++) { + + $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; + if ($feedback != $A0) { + // feedback term is non-zero + + // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must + // always be for the polynomials constructed by init_rs() + $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); + + for ($j = 1; $j < $NROOTS; $j++) { + $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS - $j])]; } } + + // Shift + array_shift($parity); + if ($feedback != $A0) { + array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); + } else { + array_push($parity, 0); + } } } - - //########################################################################## - - class QRrs { - - public static $items = array(); - - //---------------------------------------------------------------------- - public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) - { - foreach(self::$items as $rs) { - if($rs->pad != $pad) continue; - if($rs->nroots != $nroots) continue; - if($rs->mm != $symsize) continue; - if($rs->gfpoly != $gfpoly) continue; - if($rs->fcr != $fcr) continue; - if($rs->prim != $prim) continue; - - return $rs; +} + +//########################################################################## + +class QRrs +{ + + public static $items = array(); + + //---------------------------------------------------------------------- + public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + foreach (self::$items as $rs) { + if ($rs->pad != $pad) { + continue; } - $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad); - array_unshift(self::$items, $rs); + if ($rs->nroots != $nroots) { + continue; + } + + if ($rs->mm != $symsize) { + continue; + } + + if ($rs->gfpoly != $gfpoly) { + continue; + } + + if ($rs->fcr != $fcr) { + continue; + } + + if ($rs->prim != $prim) { + continue; + } return $rs; } - } \ No newline at end of file + + $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad); + array_unshift(self::$items, $rs); + + return $rs; + } +} diff --git a/include/qrcode/qrspec.php b/include/qrcode/qrspec.php index 5a0c4b3c..334bf2f6 100755 --- a/include/qrcode/qrspec.php +++ b/include/qrcode/qrspec.php @@ -13,7 +13,7 @@ * The following data / specifications are taken from * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) * or - * "Automatic identification and data capture techniques -- + * "Automatic identification and data capture techniques -- * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) * * This library is free software; you can redistribute it and/or @@ -30,498 +30,506 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('QRSPEC_VERSION_MAX', 40); - define('QRSPEC_WIDTH_MAX', 177); - - define('QRCAP_WIDTH', 0); - define('QRCAP_WORDS', 1); - define('QRCAP_REMINDER', 2); - define('QRCAP_EC', 3); - - class QRspec { - - public static $capacity = array( - array( 0, 0, 0, array( 0, 0, 0, 0)), - array( 21, 26, 0, array( 7, 10, 13, 17)), // 1 - array( 25, 44, 7, array( 10, 16, 22, 28)), - array( 29, 70, 7, array( 15, 26, 36, 44)), - array( 33, 100, 7, array( 20, 36, 52, 64)), - array( 37, 134, 7, array( 26, 48, 72, 88)), // 5 - array( 41, 172, 7, array( 36, 64, 96, 112)), - array( 45, 196, 0, array( 40, 72, 108, 130)), - array( 49, 242, 0, array( 48, 88, 132, 156)), - array( 53, 292, 0, array( 60, 110, 160, 192)), - array( 57, 346, 0, array( 72, 130, 192, 224)), //10 - array( 61, 404, 0, array( 80, 150, 224, 264)), - array( 65, 466, 0, array( 96, 176, 260, 308)), - array( 69, 532, 0, array( 104, 198, 288, 352)), - array( 73, 581, 3, array( 120, 216, 320, 384)), - array( 77, 655, 3, array( 132, 240, 360, 432)), //15 - array( 81, 733, 3, array( 144, 280, 408, 480)), - array( 85, 815, 3, array( 168, 308, 448, 532)), - array( 89, 901, 3, array( 180, 338, 504, 588)), - array( 93, 991, 3, array( 196, 364, 546, 650)), - array( 97, 1085, 3, array( 224, 416, 600, 700)), //20 - array(101, 1156, 4, array( 224, 442, 644, 750)), - array(105, 1258, 4, array( 252, 476, 690, 816)), - array(109, 1364, 4, array( 270, 504, 750, 900)), - array(113, 1474, 4, array( 300, 560, 810, 960)), - array(117, 1588, 4, array( 312, 588, 870, 1050)), //25 - array(121, 1706, 4, array( 336, 644, 952, 1110)), - array(125, 1828, 4, array( 360, 700, 1020, 1200)), - array(129, 1921, 3, array( 390, 728, 1050, 1260)), - array(133, 2051, 3, array( 420, 784, 1140, 1350)), - array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30 - array(141, 2323, 3, array( 480, 868, 1290, 1530)), - array(145, 2465, 3, array( 510, 924, 1350, 1620)), - array(149, 2611, 3, array( 540, 980, 1440, 1710)), - array(153, 2761, 3, array( 570, 1036, 1530, 1800)), - array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35 - array(161, 3034, 0, array( 600, 1120, 1680, 1980)), - array(165, 3196, 0, array( 630, 1204, 1770, 2100)), - array(169, 3362, 0, array( 660, 1260, 1860, 2220)), - array(173, 3532, 0, array( 720, 1316, 1950, 2310)), - array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40 - ); - - //---------------------------------------------------------------------- - public static function getDataLength($version, $level) - { - return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; + +define('QRSPEC_VERSION_MAX', 40); +define('QRSPEC_WIDTH_MAX', 177); + +define('QRCAP_WIDTH', 0); +define('QRCAP_WORDS', 1); +define('QRCAP_REMINDER', 2); +define('QRCAP_EC', 3); + +class QRspec +{ + + public static $capacity = array( + array(0, 0, 0, array(0, 0, 0, 0)), + array(21, 26, 0, array(7, 10, 13, 17)), // 1 + array(25, 44, 7, array(10, 16, 22, 28)), + array(29, 70, 7, array(15, 26, 36, 44)), + array(33, 100, 7, array(20, 36, 52, 64)), + array(37, 134, 7, array(26, 48, 72, 88)), // 5 + array(41, 172, 7, array(36, 64, 96, 112)), + array(45, 196, 0, array(40, 72, 108, 130)), + array(49, 242, 0, array(48, 88, 132, 156)), + array(53, 292, 0, array(60, 110, 160, 192)), + array(57, 346, 0, array(72, 130, 192, 224)), //10 + array(61, 404, 0, array(80, 150, 224, 264)), + array(65, 466, 0, array(96, 176, 260, 308)), + array(69, 532, 0, array(104, 198, 288, 352)), + array(73, 581, 3, array(120, 216, 320, 384)), + array(77, 655, 3, array(132, 240, 360, 432)), //15 + array(81, 733, 3, array(144, 280, 408, 480)), + array(85, 815, 3, array(168, 308, 448, 532)), + array(89, 901, 3, array(180, 338, 504, 588)), + array(93, 991, 3, array(196, 364, 546, 650)), + array(97, 1085, 3, array(224, 416, 600, 700)), //20 + array(101, 1156, 4, array(224, 442, 644, 750)), + array(105, 1258, 4, array(252, 476, 690, 816)), + array(109, 1364, 4, array(270, 504, 750, 900)), + array(113, 1474, 4, array(300, 560, 810, 960)), + array(117, 1588, 4, array(312, 588, 870, 1050)), //25 + array(121, 1706, 4, array(336, 644, 952, 1110)), + array(125, 1828, 4, array(360, 700, 1020, 1200)), + array(129, 1921, 3, array(390, 728, 1050, 1260)), + array(133, 2051, 3, array(420, 784, 1140, 1350)), + array(137, 2185, 3, array(450, 812, 1200, 1440)), //30 + array(141, 2323, 3, array(480, 868, 1290, 1530)), + array(145, 2465, 3, array(510, 924, 1350, 1620)), + array(149, 2611, 3, array(540, 980, 1440, 1710)), + array(153, 2761, 3, array(570, 1036, 1530, 1800)), + array(157, 2876, 0, array(570, 1064, 1590, 1890)), //35 + array(161, 3034, 0, array(600, 1120, 1680, 1980)), + array(165, 3196, 0, array(630, 1204, 1770, 2100)), + array(169, 3362, 0, array(660, 1260, 1860, 2220)), + array(173, 3532, 0, array(720, 1316, 1950, 2310)), + array(177, 3706, 0, array(750, 1372, 2040, 2430)), //40 + ); + + //---------------------------------------------------------------------- + public static function getDataLength($version, $level) + { + return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getECCLength($version, $level) + { + return self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getWidth($version) + { + return self::$capacity[$version][QRCAP_WIDTH]; + } + + //---------------------------------------------------------------------- + public static function getRemainder($version) + { + return self::$capacity[$version][QRCAP_REMINDER]; + } + + //---------------------------------------------------------------------- + public static function getMinimumVersion($size, $level) + { + + for ($i = 1; $i <= QRSPEC_VERSION_MAX; $i++) { + $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; + if ($words >= $size) { + return $i; + } + } - - //---------------------------------------------------------------------- - public static function getECCLength($version, $level) - { - return self::$capacity[$version][QRCAP_EC][$level]; + + return -1; + } + + //###################################################################### + + public static $lengthTableBits = array( + array(10, 12, 14), + array(9, 11, 13), + array(8, 16, 16), + array(8, 10, 12), + ); + + //---------------------------------------------------------------------- + public static function lengthIndicator($mode, $version) + { + if ($mode == QR_MODE_STRUCTURE) { + return 0; } - - //---------------------------------------------------------------------- - public static function getWidth($version) - { - return self::$capacity[$version][QRCAP_WIDTH]; + + if ($version <= 9) { + $l = 0; + } else if ($version <= 26) { + $l = 1; + } else { + $l = 2; } - - //---------------------------------------------------------------------- - public static function getRemainder($version) - { - return self::$capacity[$version][QRCAP_REMINDER]; + + return self::$lengthTableBits[$mode][$l]; + } + + //---------------------------------------------------------------------- + public static function maximumWords($mode, $version) + { + if ($mode == QR_MODE_STRUCTURE) { + return 3; } - - //---------------------------------------------------------------------- - public static function getMinimumVersion($size, $level) - { - - for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) { - $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; - if($words >= $size) - return $i; - } - return -1; + if ($version <= 9) { + $l = 0; + } else if ($version <= 26) { + $l = 1; + } else { + $l = 2; } - - //###################################################################### - - public static $lengthTableBits = array( - array(10, 12, 14), - array( 9, 11, 13), - array( 8, 16, 16), - array( 8, 10, 12) - ); - - //---------------------------------------------------------------------- - public static function lengthIndicator($mode, $version) - { - if ($mode == QR_MODE_STRUCTURE) - return 0; - - if ($version <= 9) { - $l = 0; - } else if ($version <= 26) { - $l = 1; - } else { - $l = 2; - } - return self::$lengthTableBits[$mode][$l]; + $bits = self::$lengthTableBits[$mode][$l]; + $words = (1 << $bits) - 1; + + if ($mode == QR_MODE_KANJI) { + $words *= 2; // the number of bytes is required } - - //---------------------------------------------------------------------- - public static function maximumWords($mode, $version) - { - if($mode == QR_MODE_STRUCTURE) - return 3; - - if($version <= 9) { - $l = 0; - } else if($version <= 26) { - $l = 1; - } else { - $l = 2; - } - $bits = self::$lengthTableBits[$mode][$l]; - $words = (1 << $bits) - 1; - - if($mode == QR_MODE_KANJI) { - $words *= 2; // the number of bytes is required - } + return $words; + } + + // Error correction code ----------------------------------------------- + // Table of the error correction code (Reed-Solomon block) + // See Table 12-16 (pp.30-36), JIS X0510:2004. + + public static $eccTable = array( + array(array(0, 0), array(0, 0), array(0, 0), array(0, 0)), + array(array(1, 0), array(1, 0), array(1, 0), array(1, 0)), // 1 + array(array(1, 0), array(1, 0), array(1, 0), array(1, 0)), + array(array(1, 0), array(1, 0), array(2, 0), array(2, 0)), + array(array(1, 0), array(2, 0), array(2, 0), array(4, 0)), + array(array(1, 0), array(2, 0), array(2, 2), array(2, 2)), // 5 + array(array(2, 0), array(4, 0), array(4, 0), array(4, 0)), + array(array(2, 0), array(4, 0), array(2, 4), array(4, 1)), + array(array(2, 0), array(2, 2), array(4, 2), array(4, 2)), + array(array(2, 0), array(3, 2), array(4, 4), array(4, 4)), + array(array(2, 2), array(4, 1), array(6, 2), array(6, 2)), //10 + array(array(4, 0), array(1, 4), array(4, 4), array(3, 8)), + array(array(2, 2), array(6, 2), array(4, 6), array(7, 4)), + array(array(4, 0), array(8, 1), array(8, 4), array(12, 4)), + array(array(3, 1), array(4, 5), array(11, 5), array(11, 5)), + array(array(5, 1), array(5, 5), array(5, 7), array(11, 7)), //15 + array(array(5, 1), array(7, 3), array(15, 2), array(3, 13)), + array(array(1, 5), array(10, 1), array(1, 15), array(2, 17)), + array(array(5, 1), array(9, 4), array(17, 1), array(2, 19)), + array(array(3, 4), array(3, 11), array(17, 4), array(9, 16)), + array(array(3, 5), array(3, 13), array(15, 5), array(15, 10)), //20 + array(array(4, 4), array(17, 0), array(17, 6), array(19, 6)), + array(array(2, 7), array(17, 0), array(7, 16), array(34, 0)), + array(array(4, 5), array(4, 14), array(11, 14), array(16, 14)), + array(array(6, 4), array(6, 14), array(11, 16), array(30, 2)), + array(array(8, 4), array(8, 13), array(7, 22), array(22, 13)), //25 + array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), + array(array(8, 4), array(22, 3), array(8, 26), array(12, 28)), + array(array(3, 10), array(3, 23), array(4, 31), array(11, 31)), + array(array(7, 7), array(21, 7), array(1, 37), array(19, 26)), + array(array(5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 + array(array(13, 3), array(2, 29), array(42, 1), array(23, 28)), + array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), + array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), + array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), + array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 + array(array(6, 14), array(6, 34), array(46, 10), array(2, 64)), + array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), + array(array(4, 18), array(13, 32), array(48, 14), array(42, 32)), + array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), + array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)), //40 + ); + + //---------------------------------------------------------------------- + // CACHEABLE!!! + + public static function getEccSpec($version, $level, array &$spec) + { + if (count($spec) < 5) { + $spec = array(0, 0, 0, 0, 0); + } - return $words; + $b1 = self::$eccTable[$version][$level][0]; + $b2 = self::$eccTable[$version][$level][1]; + $data = self::getDataLength($version, $level); + $ecc = self::getECCLength($version, $level); + + if ($b2 == 0) { + $spec[0] = $b1; + $spec[1] = (int) ($data / $b1); + $spec[2] = (int) ($ecc / $b1); + $spec[3] = 0; + $spec[4] = 0; + } else { + $spec[0] = $b1; + $spec[1] = (int) ($data / ($b1 + $b2)); + $spec[2] = (int) ($ecc / ($b1 + $b2)); + $spec[3] = $b2; + $spec[4] = $spec[1] + 1; } + } + + // Alignment pattern --------------------------------------------------- + + // Positions of alignment patterns. + // This array includes only the second and the third position of the + // alignment patterns. Rest of them can be calculated from the distance + // between them. + + // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. + + public static $alignmentPattern = array( + array(0, 0), + array(0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 + array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 + array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 + array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 + array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 + array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 + array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 + array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 + ); + + /** -------------------------------------------------------------------- + * Put an alignment marker. + * @param frame + * @param width + * @param ox,oy center coordinate of the pattern + */ + public static function putAlignmentMarker(array &$frame, $ox, $oy) + { + $finder = array( + "\xa1\xa1\xa1\xa1\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa0\xa1\xa0\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa1\xa1\xa1\xa1", + ); - // Error correction code ----------------------------------------------- - // Table of the error correction code (Reed-Solomon block) - // See Table 12-16 (pp.30-36), JIS X0510:2004. - - public static $eccTable = array( - array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)), - array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1 - array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), - array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)), - array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)), - array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5 - array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)), - array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)), - array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)), - array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)), - array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10 - array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)), - array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)), - array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)), - array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)), - array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15 - array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)), - array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)), - array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)), - array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)), - array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20 - array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)), - array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)), - array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)), - array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)), - array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25 - array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), - array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)), - array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), - array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)), - array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 - array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)), - array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), - array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), - array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), - array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 - array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), - array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), - array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), - array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), - array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40 - ); - - //---------------------------------------------------------------------- - // CACHEABLE!!! - - public static function getEccSpec($version, $level, array &$spec) - { - if (count($spec) < 5) { - $spec = array(0,0,0,0,0); - } + $yStart = $oy - 2; + $xStart = $ox - 2; - $b1 = self::$eccTable[$version][$level][0]; - $b2 = self::$eccTable[$version][$level][1]; - $data = self::getDataLength($version, $level); - $ecc = self::getECCLength($version, $level); - - if($b2 == 0) { - $spec[0] = $b1; - $spec[1] = (int)($data / $b1); - $spec[2] = (int)($ecc / $b1); - $spec[3] = 0; - $spec[4] = 0; - } else { - $spec[0] = $b1; - $spec[1] = (int)($data / ($b1 + $b2)); - $spec[2] = (int)($ecc / ($b1 + $b2)); - $spec[3] = $b2; - $spec[4] = $spec[1] + 1; - } + for ($y = 0; $y < 5; $y++) { + QRstr::set($frame, $xStart, $yStart + $y, $finder[$y]); } + } - // Alignment pattern --------------------------------------------------- - - // Positions of alignment patterns. - // This array includes only the second and the third position of the - // alignment patterns. Rest of them can be calculated from the distance - // between them. - - // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. - - public static $alignmentPattern = array( - array( 0, 0), - array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 - array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 - array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 - array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 - array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 - array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 - array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 - array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 - ); - - - /** -------------------------------------------------------------------- - * Put an alignment marker. - * @param frame - * @param width - * @param ox,oy center coordinate of the pattern - */ - public static function putAlignmentMarker(array &$frame, $ox, $oy) - { - $finder = array( - "\xa1\xa1\xa1\xa1\xa1", - "\xa1\xa0\xa0\xa0\xa1", - "\xa1\xa0\xa1\xa0\xa1", - "\xa1\xa0\xa0\xa0\xa1", - "\xa1\xa1\xa1\xa1\xa1" - ); - - $yStart = $oy-2; - $xStart = $ox-2; - - for($y=0; $y<5; $y++) { - QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]); - } + //---------------------------------------------------------------------- + public static function putAlignmentPattern($version, &$frame, $width) + { + if ($version < 2) { + return; } - //---------------------------------------------------------------------- - public static function putAlignmentPattern($version, &$frame, $width) - { - if($version < 2) - return; + $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; + if ($d < 0) { + $w = 2; + } else { + $w = (int) (($width - self::$alignmentPattern[$version][0]) / $d + 2); + } - $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; - if($d < 0) { - $w = 2; - } else { - $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2); - } + if ($w * $w - 3 == 1) { + $x = self::$alignmentPattern[$version][0]; + $y = self::$alignmentPattern[$version][0]; + self::putAlignmentMarker($frame, $x, $y); + return; + } - if($w * $w - 3 == 1) { - $x = self::$alignmentPattern[$version][0]; - $y = self::$alignmentPattern[$version][0]; - self::putAlignmentMarker($frame, $x, $y); - return; - } + $cx = self::$alignmentPattern[$version][0]; + for ($x = 1; $x < $w - 1; $x++) { + self::putAlignmentMarker($frame, 6, $cx); + self::putAlignmentMarker($frame, $cx, 6); + $cx += $d; + } + $cy = self::$alignmentPattern[$version][0]; + for ($y = 0; $y < $w - 1; $y++) { $cx = self::$alignmentPattern[$version][0]; - for($x=1; $x<$w - 1; $x++) { - self::putAlignmentMarker($frame, 6, $cx); - self::putAlignmentMarker($frame, $cx, 6); + for ($x = 0; $x < $w - 1; $x++) { + self::putAlignmentMarker($frame, $cx, $cy); $cx += $d; } + $cy += $d; + } + } - $cy = self::$alignmentPattern[$version][0]; - for($y=0; $y<$w-1; $y++) { - $cx = self::$alignmentPattern[$version][0]; - for($x=0; $x<$w-1; $x++) { - self::putAlignmentMarker($frame, $cx, $cy); - $cx += $d; - } - $cy += $d; - } + // Version information pattern ----------------------------------------- + + // Version information pattern (BCH coded). + // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. + + // size: [QRSPEC_VERSION_MAX - 6] + + public static $versionPattern = array( + 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, + 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, + 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, + 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, + 0x27541, 0x28c69, + ); + + //---------------------------------------------------------------------- + public static function getVersionPattern($version) + { + if ($version < 7 || $version > QRSPEC_VERSION_MAX) { + return 0; } - // Version information pattern ----------------------------------------- - - // Version information pattern (BCH coded). - // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. - - // size: [QRSPEC_VERSION_MAX - 6] - - public static $versionPattern = array( - 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, - 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, - 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, - 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, - 0x27541, 0x28c69 - ); + return self::$versionPattern[$version - 7]; + } - //---------------------------------------------------------------------- - public static function getVersionPattern($version) - { - if($version < 7 || $version > QRSPEC_VERSION_MAX) - return 0; + // Format information -------------------------------------------------- + // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) - return self::$versionPattern[$version -7]; + public static $formatInfo = array( + array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), + array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), + array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), + array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b), + ); + + public static function getFormatInfo($mask, $level) + { + if ($mask < 0 || $mask > 7) { + return 0; } - // Format information -------------------------------------------------- - // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) - - public static $formatInfo = array( - array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), - array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), - array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), - array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) + if ($level < 0 || $level > 3) { + return 0; + } + + return self::$formatInfo[$level][$mask]; + } + + // Frame --------------------------------------------------------------- + // Cache of initial frames. + + public static $frames = array(); + + /** -------------------------------------------------------------------- + * Put a finder pattern. + * @param frame + * @param width + * @param ox,oy upper-left coordinate of the pattern + */ + public static function putFinderPattern(&$frame, $ox, $oy) + { + $finder = array( + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", ); - public static function getFormatInfo($mask, $level) - { - if($mask < 0 || $mask > 7) - return 0; - - if($level < 0 || $level > 3) - return 0; + for ($y = 0; $y < 7; $y++) { + QRstr::set($frame, $ox, $oy + $y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function createFrame($version) + { + $width = self::$capacity[$version][QRCAP_WIDTH]; + $frameLine = str_repeat("\0", $width); + $frame = array_fill(0, $width, $frameLine); + + // Finder pattern + self::putFinderPattern($frame, 0, 0); + self::putFinderPattern($frame, $width - 7, 0); + self::putFinderPattern($frame, 0, $width - 7); + + // Separator + $yOffset = $width - 7; + + for ($y = 0; $y < 7; $y++) { + $frame[$y][7] = "\xc0"; + $frame[$y][$width - 8] = "\xc0"; + $frame[$yOffset][7] = "\xc0"; + $yOffset++; + } + + $setPattern = str_repeat("\xc0", 8); - return self::$formatInfo[$level][$mask]; + QRstr::set($frame, 0, 7, $setPattern); + QRstr::set($frame, $width - 8, 7, $setPattern); + QRstr::set($frame, 0, $width - 8, $setPattern); + + // Format info + $setPattern = str_repeat("\x84", 9); + QRstr::set($frame, 0, 8, $setPattern); + QRstr::set($frame, $width - 8, 8, $setPattern, 8); + + $yOffset = $width - 8; + + for ($y = 0; $y < 8; $y++, $yOffset++) { + $frame[$y][8] = "\x84"; + $frame[$yOffset][8] = "\x84"; } - // Frame --------------------------------------------------------------- - // Cache of initial frames. - - public static $frames = array(); - - /** -------------------------------------------------------------------- - * Put a finder pattern. - * @param frame - * @param width - * @param ox,oy upper-left coordinate of the pattern - */ - public static function putFinderPattern(&$frame, $ox, $oy) - { - $finder = array( - "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", - "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", - "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", - "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", - "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", - "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", - "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" - ); - - for($y=0; $y<7; $y++) { - QRstr::set($frame, $ox, $oy+$y, $finder[$y]); - } + // Timing pattern + + for ($i = 1; $i < $width - 15; $i++) { + $frame[6][7 + $i] = chr(0x90 | ($i & 1)); + $frame[7 + $i][6] = chr(0x90 | ($i & 1)); } - //---------------------------------------------------------------------- - public static function createFrame($version) - { - $width = self::$capacity[$version][QRCAP_WIDTH]; - $frameLine = str_repeat ("\0", $width); - $frame = array_fill(0, $width, $frameLine); - - // Finder pattern - self::putFinderPattern($frame, 0, 0); - self::putFinderPattern($frame, $width - 7, 0); - self::putFinderPattern($frame, 0, $width - 7); - - // Separator - $yOffset = $width - 7; - - for($y=0; $y<7; $y++) { - $frame[$y][7] = "\xc0"; - $frame[$y][$width - 8] = "\xc0"; - $frame[$yOffset][7] = "\xc0"; - $yOffset++; - } - - $setPattern = str_repeat("\xc0", 8); - - QRstr::set($frame, 0, 7, $setPattern); - QRstr::set($frame, $width-8, 7, $setPattern); - QRstr::set($frame, 0, $width - 8, $setPattern); - - // Format info - $setPattern = str_repeat("\x84", 9); - QRstr::set($frame, 0, 8, $setPattern); - QRstr::set($frame, $width - 8, 8, $setPattern, 8); - - $yOffset = $width - 8; - - for($y=0; $y<8; $y++,$yOffset++) { - $frame[$y][8] = "\x84"; - $frame[$yOffset][8] = "\x84"; - } + // Alignment pattern + self::putAlignmentPattern($version, $frame, $width); - // Timing pattern - - for($i=1; $i<$width-15; $i++) { - $frame[6][7+$i] = chr(0x90 | ($i & 1)); - $frame[7+$i][6] = chr(0x90 | ($i & 1)); - } - - // Alignment pattern - self::putAlignmentPattern($version, $frame, $width); - - // Version information - if($version >= 7) { - $vinf = self::getVersionPattern($version); - - $v = $vinf; - - for($x=0; $x<6; $x++) { - for($y=0; $y<3; $y++) { - $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1)); - $v = $v >> 1; - } + // Version information + if ($version >= 7) { + $vinf = self::getVersionPattern($version); + + $v = $vinf; + + for ($x = 0; $x < 6; $x++) { + for ($y = 0; $y < 3; $y++) { + $frame[($width - 11) + $y][$x] = chr(0x88 | ($v & 1)); + $v = $v >> 1; } + } - $v = $vinf; - for($y=0; $y<6; $y++) { - for($x=0; $x<3; $x++) { - $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1)); - $v = $v >> 1; - } + $v = $vinf; + for ($y = 0; $y < 6; $y++) { + for ($x = 0; $x < 3; $x++) { + $frame[$y][$x + ($width - 11)] = chr(0x88 | ($v & 1)); + $v = $v >> 1; } } - - // and a little bit... - $frame[$width - 8][8] = "\x81"; - - return $frame; } - //---------------------------------------------------------------------- - public static function debug($frame, $binary_mode = false) - { - if ($binary_mode) { - - foreach ($frame as &$frameLine) { - $frameLine = join('  ', explode('0', $frameLine)); - $frameLine = join('██', explode('1', $frameLine)); - } - - ?> + // and a little bit... + $frame[$width - 8][8] = "\x81"; + + return $frame; + } + + //---------------------------------------------------------------------- + public static function debug($frame, $binary_mode = false) + { + if ($binary_mode) { + + foreach ($frame as &$frameLine) { + $frameLine = join('  ', explode('0', $frameLine)); + $frameLine = join('██', explode('1', $frameLine)); + } + + ?>


        '; - echo join("
        ", $frame); - echo '






'; - - } else { - - foreach ($frame as &$frameLine) { - $frameLine = join(' ', explode("\xc0", $frameLine)); - $frameLine = join('', explode("\xc1", $frameLine)); - $frameLine = join(' ', explode("\xa0", $frameLine)); - $frameLine = join('', explode("\xa1", $frameLine)); - $frameLine = join('', explode("\x84", $frameLine)); //format 0 - $frameLine = join('', explode("\x85", $frameLine)); //format 1 - $frameLine = join('', explode("\x81", $frameLine)); //special bit - $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 - $frameLine = join('', explode("\x91", $frameLine)); //clock 1 - $frameLine = join(' ', explode("\x88", $frameLine)); //version - $frameLine = join('', explode("\x89", $frameLine)); //version - $frameLine = join('♦', explode("\x01", $frameLine)); - $frameLine = join('⋅', explode("\0", $frameLine)); - } - - ?> +echo '



        '; + echo join("
        ", $frame); + echo '






'; + + } else { + + foreach ($frame as &$frameLine) { + $frameLine = join(' ', explode("\xc0", $frameLine)); + $frameLine = join('', explode("\xc1", $frameLine)); + $frameLine = join(' ', explode("\xa0", $frameLine)); + $frameLine = join('', explode("\xa1", $frameLine)); + $frameLine = join('', explode("\x84", $frameLine)); //format 0 + $frameLine = join('', explode("\x85", $frameLine)); //format 1 + $frameLine = join('', explode("\x81", $frameLine)); //special bit + $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 + $frameLine = join('', explode("\x91", $frameLine)); //clock 1 + $frameLine = join(' ', explode("\x88", $frameLine)); //version + $frameLine = join('', explode("\x89", $frameLine)); //version + $frameLine = join('♦', explode("\x01", $frameLine)); + $frameLine = join('⋅', explode("\0", $frameLine)); + } + + ?> "; - echo join("
", $frame); - echo "
"; - - } - } +echo "
";
+            echo join("
", $frame); + echo "
"; - //---------------------------------------------------------------------- - public static function serial($frame) - { - return gzcompress(join("\n", $frame), 9); } - - //---------------------------------------------------------------------- - public static function unserial($code) - { - return explode("\n", gzuncompress($code)); + } + + //---------------------------------------------------------------------- + public static function serial($frame) + { + return gzcompress(join("\n", $frame), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + return explode("\n", gzuncompress($code)); + } + + //---------------------------------------------------------------------- + public static function newFrame($version) + { + if ($version < 1 || $version > QRSPEC_VERSION_MAX) { + return null; } - - //---------------------------------------------------------------------- - public static function newFrame($version) - { - if($version < 1 || $version > QRSPEC_VERSION_MAX) - return null; - - if(!isset(self::$frames[$version])) { - - $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat'; - - if (QR_CACHEABLE) { - if (file_exists($fileName)) { - self::$frames[$version] = self::unserial(file_get_contents($fileName)); - } else { - self::$frames[$version] = self::createFrame($version); - file_put_contents($fileName, self::serial(self::$frames[$version])); - } + + if (!isset(self::$frames[$version])) { + + $fileName = QR_CACHE_DIR . 'frame_' . $version . '.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + self::$frames[$version] = self::unserial(file_get_contents($fileName)); } else { self::$frames[$version] = self::createFrame($version); + file_put_contents($fileName, self::serial(self::$frames[$version])); } + } else { + self::$frames[$version] = self::createFrame($version); } - - if(is_null(self::$frames[$version])) - return null; + } - return self::$frames[$version]; + if (is_null(self::$frames[$version])) { + return null; } - //---------------------------------------------------------------------- - public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; } - public static function rsBlockNum1($spec) { return $spec[0]; } - public static function rsDataCodes1($spec) { return $spec[1]; } - public static function rsEccCodes1($spec) { return $spec[2]; } - public static function rsBlockNum2($spec) { return $spec[3]; } - public static function rsDataCodes2($spec) { return $spec[4]; } - public static function rsEccCodes2($spec) { return $spec[2]; } - public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); } - public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; } - - } \ No newline at end of file + return self::$frames[$version]; + } + + //---------------------------------------------------------------------- + public static function rsBlockNum($spec) + {return $spec[0] + $spec[3];} + public static function rsBlockNum1($spec) + {return $spec[0];} + public static function rsDataCodes1($spec) + {return $spec[1];} + public static function rsEccCodes1($spec) + {return $spec[2];} + public static function rsBlockNum2($spec) + {return $spec[3];} + public static function rsDataCodes2($spec) + {return $spec[4];} + public static function rsEccCodes2($spec) + {return $spec[2];} + public static function rsDataLength($spec) + {return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]);} + public static function rsEccLength($spec) + {return ($spec[0] + $spec[3]) * $spec[2];} + +} \ No newline at end of file diff --git a/include/qrcode/qrsplit.php b/include/qrcode/qrsplit.php index 8099c416..c5a005ed 100755 --- a/include/qrcode/qrsplit.php +++ b/include/qrcode/qrsplit.php @@ -13,7 +13,7 @@ * The following data / specifications are taken from * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) * or - * "Automatic identification and data capture techniques -- + * "Automatic identification and data capture techniques -- * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) * * This library is free software; you can redistribute it and/or @@ -30,282 +30,301 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - class QRsplit { - - public $dataStr = ''; - public $input; - public $modeHint; - - //---------------------------------------------------------------------- - public function __construct($dataStr, $input, $modeHint) - { - $this->dataStr = $dataStr; - $this->input = $input; - $this->modeHint = $modeHint; +class QRsplit +{ + + public $dataStr = ''; + public $input; + public $modeHint; + + //---------------------------------------------------------------------- + public function __construct($dataStr, $input, $modeHint) + { + $this->dataStr = $dataStr; + $this->input = $input; + $this->modeHint = $modeHint; + } + + //---------------------------------------------------------------------- + public static function isdigitat($str, $pos) + { + if ($pos >= strlen($str)) { + return false; } - - //---------------------------------------------------------------------- - public static function isdigitat($str, $pos) - { - if ($pos >= strlen($str)) - return false; - - return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9'))); + + return ((ord($str[$pos]) >= ord('0')) && (ord($str[$pos]) <= ord('9'))); + } + + //---------------------------------------------------------------------- + public static function isalnumat($str, $pos) + { + if ($pos >= strlen($str)) { + return false; } - - //---------------------------------------------------------------------- - public static function isalnumat($str, $pos) - { - if ($pos >= strlen($str)) - return false; - - return (QRinput::lookAnTable(ord($str[$pos])) >= 0); + + return (QRinput::lookAnTable(ord($str[$pos])) >= 0); + } + + //---------------------------------------------------------------------- + public function identifyMode($pos) + { + if ($pos >= strlen($this->dataStr)) { + return QR_MODE_NUL; } - //---------------------------------------------------------------------- - public function identifyMode($pos) - { - if ($pos >= strlen($this->dataStr)) - return QR_MODE_NUL; - - $c = $this->dataStr[$pos]; - - if(self::isdigitat($this->dataStr, $pos)) { - return QR_MODE_NUM; - } else if(self::isalnumat($this->dataStr, $pos)) { - return QR_MODE_AN; - } else if($this->modeHint == QR_MODE_KANJI) { - - if ($pos+1 < strlen($this->dataStr)) - { - $d = $this->dataStr[$pos+1]; - $word = (ord($c) << 8) | ord($d); - if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { - return QR_MODE_KANJI; - } + $c = $this->dataStr[$pos]; + + if (self::isdigitat($this->dataStr, $pos)) { + return QR_MODE_NUM; + } else if (self::isalnumat($this->dataStr, $pos)) { + return QR_MODE_AN; + } else if ($this->modeHint == QR_MODE_KANJI) { + + if ($pos + 1 < strlen($this->dataStr)) { + $d = $this->dataStr[$pos + 1]; + $word = (ord($c) << 8) | ord($d); + if (($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { + return QR_MODE_KANJI; } } + } - return QR_MODE_8; - } - - //---------------------------------------------------------------------- - public function eatNum() - { - $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + return QR_MODE_8; + } - $p = 0; - while(self::isdigitat($this->dataStr, $p)) { - $p++; - } - - $run = $p; - $mode = $this->identifyMode($p); - - if($mode == QR_MODE_8) { - $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln - + QRinput::estimateBitsMode8(1) // + 4 + l8 - - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 - if($dif > 0) { - return $this->eat8(); - } + //---------------------------------------------------------------------- + public function eatNum() + { + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + while (self::isdigitat($this->dataStr, $p)) { + $p++; + } + + $run = $p; + $mode = $this->identifyMode($p); + + if ($mode == QR_MODE_8) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if ($dif > 0) { + return $this->eat8(); } - if($mode == QR_MODE_AN) { - $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln - + QRinput::estimateBitsModeAn(1) // + 4 + la - - QRinput::estimateBitsModeAn($run + 1);// - 4 - la - if($dif > 0) { - return $this->eatAn(); - } + } + if ($mode == QR_MODE_AN) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsModeAn(1) // + 4 + la + - QRinput::estimateBitsModeAn($run + 1); // - 4 - la + if ($dif > 0) { + return $this->eatAn(); } - - $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); - if($ret < 0) - return -1; + } - return $run; + $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); + if ($ret < 0) { + return -1; } - - //---------------------------------------------------------------------- - public function eatAn() - { - $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); - $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); - - $p = 0; - - while(self::isalnumat($this->dataStr, $p)) { - if(self::isdigitat($this->dataStr, $p)) { - $q = $p; - while(self::isdigitat($this->dataStr, $q)) { - $q++; - } - - $dif = QRinput::estimateBitsModeAn($p) // + 4 + la - + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln - - QRinput::estimateBitsModeAn($q); // - 4 - la - - if($dif < 0) { - break; - } else { - $p = $q; - } + + return $run; + } + + //---------------------------------------------------------------------- + public function eatAn() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + + while (self::isalnumat($this->dataStr, $p)) { + if (self::isdigitat($this->dataStr, $p)) { + $q = $p; + while (self::isdigitat($this->dataStr, $q)) { + $q++; + } + + $dif = QRinput::estimateBitsModeAn($p) // + 4 + la + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsModeAn($q); // - 4 - la + + if ($dif < 0) { + break; } else { - $p++; + $p = $q; } + } else { + $p++; } + } - $run = $p; + $run = $p; - if(!self::isalnumat($this->dataStr, $p)) { - $dif = QRinput::estimateBitsModeAn($run) + 4 + $la - + QRinput::estimateBitsMode8(1) // + 4 + l8 - - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 - if($dif > 0) { - return $this->eat8(); - } + if (!self::isalnumat($this->dataStr, $p)) { + $dif = QRinput::estimateBitsModeAn($run) + 4 + $la + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if ($dif > 0) { + return $this->eat8(); } + } - $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); - if($ret < 0) - return -1; + $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); + if ($ret < 0) { + return -1; + } + + return $run; + } - return $run; + //---------------------------------------------------------------------- + public function eatKanji() + { + $p = 0; + + while ($this->identifyMode($p) == QR_MODE_KANJI) { + $p += 2; } - - //---------------------------------------------------------------------- - public function eatKanji() - { - $p = 0; - - while($this->identifyMode($p) == QR_MODE_KANJI) { - $p += 2; - } - - $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); - if($ret < 0) - return -1; - return $run; + $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); + if ($ret < 0) { + return -1; } - //---------------------------------------------------------------------- - public function eat8() - { - $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); - $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); - - $p = 1; - $dataStrLen = strlen($this->dataStr); - - while($p < $dataStrLen) { - - $mode = $this->identifyMode($p); - if($mode == QR_MODE_KANJI) { + return $run; + } + + //---------------------------------------------------------------------- + public function eat8() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 1; + $dataStrLen = strlen($this->dataStr); + + while ($p < $dataStrLen) { + + $mode = $this->identifyMode($p); + if ($mode == QR_MODE_KANJI) { + break; + } + if ($mode == QR_MODE_NUM) { + $q = $p; + while (self::isdigitat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if ($dif < 0) { break; + } else { + $p = $q; } - if($mode == QR_MODE_NUM) { - $q = $p; - while(self::isdigitat($this->dataStr, $q)) { - $q++; - } - $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 - + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln - - QRinput::estimateBitsMode8($q); // - 4 - l8 - if($dif < 0) { - break; - } else { - $p = $q; - } - } else if($mode == QR_MODE_AN) { - $q = $p; - while(self::isalnumat($this->dataStr, $q)) { - $q++; - } - $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 - + QRinput::estimateBitsModeAn($q - $p) + 4 + $la - - QRinput::estimateBitsMode8($q); // - 4 - l8 - if($dif < 0) { - break; - } else { - $p = $q; - } + } else if ($mode == QR_MODE_AN) { + $q = $p; + while (self::isalnumat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeAn($q - $p) + 4 + $la + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if ($dif < 0) { + break; } else { - $p++; + $p = $q; } + } else { + $p++; } + } - $run = $p; - $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); - - if($ret < 0) - return -1; + $run = $p; + $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); - return $run; + if ($ret < 0) { + return -1; } - //---------------------------------------------------------------------- - public function splitString() - { - while (strlen($this->dataStr) > 0) - { - if($this->dataStr == '') - return 0; - - $mode = $this->identifyMode(0); - - switch ($mode) { - case QR_MODE_NUM: $length = $this->eatNum(); break; - case QR_MODE_AN: $length = $this->eatAn(); break; - case QR_MODE_KANJI: - if ($hint == QR_MODE_KANJI) - $length = $this->eatKanji(); - else $length = $this->eat8(); - break; - default: $length = $this->eat8(); break; - - } + return $run; + } - if($length == 0) return 0; - if($length < 0) return -1; - - $this->dataStr = substr($this->dataStr, $length); + //---------------------------------------------------------------------- + public function splitString() + { + while (strlen($this->dataStr) > 0) { + if ($this->dataStr == '') { + return 0; } - } - //---------------------------------------------------------------------- - public function toUpper() - { - $stringLen = strlen($this->dataStr); - $p = 0; - - while ($p<$stringLen) { - $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); - if($mode == QR_MODE_KANJI) { - $p += 2; - } else { - if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { - $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); + $mode = $this->identifyMode(0); + + switch ($mode) { + case QR_MODE_NUM:$length = $this->eatNum(); + break; + case QR_MODE_AN:$length = $this->eatAn(); + break; + case QR_MODE_KANJI: + if ($hint == QR_MODE_KANJI) { + $length = $this->eatKanji(); + } else { + $length = $this->eat8(); } - $p++; - } + + break; + default:$length = $this->eat8(); + break; + + } + + if ($length == 0) { + return 0; + } + + if ($length < 0) { + return -1; } - return $this->dataStr; + $this->dataStr = substr($this->dataStr, $length); } + } + + //---------------------------------------------------------------------- + public function toUpper() + { + $stringLen = strlen($this->dataStr); + $p = 0; - //---------------------------------------------------------------------- - public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) - { - if(is_null($string) || $string == '\0' || $string == '') { - throw new Exception('empty string!!!'); + while ($p < $stringLen) { + $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); + if ($mode == QR_MODE_KANJI) { + $p += 2; + } else { + if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { + $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); + } + $p++; } + } - $split = new QRsplit($string, $input, $modeHint); - - if(!$casesensitive) - $split->toUpper(); - - return $split->splitString(); + return $this->dataStr; + } + + //---------------------------------------------------------------------- + public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) + { + if (is_null($string) || $string == '\0' || $string == '') { + throw new Exception('empty string!!!'); } - } \ No newline at end of file + + $split = new QRsplit($string, $input, $modeHint); + + if (!$casesensitive) { + $split->toUpper(); + } + + return $split->splitString(); + } +} diff --git a/include/qrcode/qrtools.php b/include/qrcode/qrtools.php index e0412c43..3203f274 100755 --- a/include/qrcode/qrtools.php +++ b/include/qrcode/qrtools.php @@ -22,151 +22,157 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - class QRtools { - - //---------------------------------------------------------------------- - public static function binarize($frame) - { - $len = count($frame); - foreach ($frame as &$frameLine) { - - for($i=0; $i<$len; $i++) { - $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0'; - } +class QRtools +{ + + //---------------------------------------------------------------------- + public static function binarize($frame) + { + $len = count($frame); + foreach ($frame as &$frameLine) { + + for ($i = 0; $i < $len; $i++) { + $frameLine[$i] = (ord($frameLine[$i]) & 1) ? '1' : '0'; } - - return $frame; } - - //---------------------------------------------------------------------- - public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') - { - $barcode_array = array(); - - if (!is_array($mode)) - $mode = explode(',', $mode); - - $eccLevel = 'L'; - - if (count($mode) > 1) { - $eccLevel = $mode[1]; - } - - $qrTab = QRcode::text($code, false, $eccLevel); - $size = count($qrTab); - - $barcode_array['num_rows'] = $size; - $barcode_array['num_cols'] = $size; - $barcode_array['bcode'] = array(); - - foreach ($qrTab as $line) { - $arrAdd = array(); - foreach(str_split($line) as $char) - $arrAdd[] = ($char=='1')?1:0; - $barcode_array['bcode'][] = $arrAdd; - } - - return $barcode_array; + + return $frame; + } + + //---------------------------------------------------------------------- + public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') + { + $barcode_array = array(); + + if (!is_array($mode)) { + $mode = explode(',', $mode); } - - //---------------------------------------------------------------------- - public static function clearCache() - { - self::$frames = array(); + + $eccLevel = 'L'; + + if (count($mode) > 1) { + $eccLevel = $mode[1]; } - - //---------------------------------------------------------------------- - public static function buildCache() - { - QRtools::markTime('before_build_cache'); - - $mask = new QRmask(); - for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) { - $frame = QRspec::newFrame($a); - if (QR_IMAGE) { - $fileName = QR_CACHE_DIR.'frame_'.$a.'.png'; - QRimage::png(self::binarize($frame), $fileName, 1, 0); - } - - $width = count($frame); - $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); - for ($maskNo=0; $maskNo<8; $maskNo++) - $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + + $qrTab = QRcode::text($code, false, $eccLevel); + $size = count($qrTab); + + $barcode_array['num_rows'] = $size; + $barcode_array['num_cols'] = $size; + $barcode_array['bcode'] = array(); + + foreach ($qrTab as $line) { + $arrAdd = array(); + foreach (str_split($line) as $char) { + $arrAdd[] = ($char == '1') ? 1 : 0; } - - QRtools::markTime('after_build_cache'); + + $barcode_array['bcode'][] = $arrAdd; } - //---------------------------------------------------------------------- - public static function log($outfile, $err) - { - if (QR_LOG_DIR !== false) { - if ($err != '') { - if ($outfile !== false) { - file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); - } else { - file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); - } - } + return $barcode_array; + } + + //---------------------------------------------------------------------- + public static function clearCache() + { + self::$frames = array(); + } + + //---------------------------------------------------------------------- + public static function buildCache() + { + QRtools::markTime('before_build_cache'); + + $mask = new QRmask(); + for ($a = 1; $a <= QRSPEC_VERSION_MAX; $a++) { + $frame = QRspec::newFrame($a); + if (QR_IMAGE) { + $fileName = QR_CACHE_DIR . 'frame_' . $a . '.png'; + QRimage::png(self::binarize($frame), $fileName, 1, 0); } - } - - //---------------------------------------------------------------------- - public static function dumpMask($frame) - { + $width = count($frame); - for($y=0;$y<$width;$y++) { - for($x=0;$x<$width;$x++) { - echo ord($frame[$y][$x]).','; + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + for ($maskNo = 0; $maskNo < 8; $maskNo++) { + $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + } + + } + + QRtools::markTime('after_build_cache'); + } + + //---------------------------------------------------------------------- + public static function log($outfile, $err) + { + if (QR_LOG_DIR !== false) { + if ($err != '') { + if ($outfile !== false) { + file_put_contents(QR_LOG_DIR . basename($outfile) . '-errors.txt', date('Y-m-d H:i:s') . ': ' . $err, FILE_APPEND); + } else { + file_put_contents(QR_LOG_DIR . 'errors.txt', date('Y-m-d H:i:s') . ': ' . $err, FILE_APPEND); } } } - - //---------------------------------------------------------------------- - public static function markTime($markerId) - { - list($usec, $sec) = explode(" ", microtime()); - $time = ((float)$usec + (float)$sec); - - if (!isset($GLOBALS['qr_time_bench'])) - $GLOBALS['qr_time_bench'] = array(); - - $GLOBALS['qr_time_bench'][$markerId] = $time; + } + + //---------------------------------------------------------------------- + public static function dumpMask($frame) + { + $width = count($frame); + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { + echo ord($frame[$y][$x]) . ','; + } } - - //---------------------------------------------------------------------- - public static function timeBenchmark() - { - self::markTime('finish'); - - $lastTime = 0; - $startTime = 0; - $p = 0; - - echo ' + } + + //---------------------------------------------------------------------- + public static function markTime($markerId) + { + list($usec, $sec) = explode(" ", microtime()); + $time = ((float) $usec + (float) $sec); + + if (!isset($GLOBALS['qr_time_bench'])) { + $GLOBALS['qr_time_bench'] = array(); + } + + $GLOBALS['qr_time_bench'][$markerId] = $time; + } + + //---------------------------------------------------------------------- + public static function timeBenchmark() + { + self::markTime('finish'); + + $lastTime = 0; + $startTime = 0; + $p = 0; + + echo '
'; - foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) { - if ($p > 0) { - echo ''; - } else { - $startTime = $thisTime; - } - - $p++; - $lastTime = $thisTime; + foreach ($GLOBALS['qr_time_bench'] as $markerId => $thisTime) { + if ($p > 0) { + echo ''; + } else { + $startTime = $thisTime; } - - echo ' - + + $p++; + $lastTime = $thisTime; + } + + echo ' +
BENCHMARK
till '.$markerId.': '.number_format($thisTime-$lastTime, 6).'s
till ' . $markerId . ': ' . number_format($thisTime - $lastTime, 6) . 's
TOTAL: '.number_format($lastTime-$startTime, 6).'s
TOTAL: ' . number_format($lastTime - $startTime, 6) . 's
'; - } - } - - //########################################################################## - - QRtools::markTime('start'); - \ No newline at end of file + +} + +//########################################################################## + +QRtools::markTime('start'); diff --git a/include/taglib/adminname.lib.php b/include/taglib/adminname.lib.php index ebc825cd..a3c2feba 100755 --- a/include/taglib/adminname.lib.php +++ b/include/taglib/adminname.lib.php @@ -1,4 +1,4 @@ ->dede>> -责任编辑 -仅内容模板 + +/*>>dede>> +责任编辑 +仅内容模板 V55,V56,V57 获得责任编辑名称 -{dede:adminname /} +{dede:adminname /} - + >>dede>>*/ function lib_adminname(&$ctag, &$refObj) { global $dsql; - if(empty($refObj->Fields['dutyadmin'])) - { + if (empty($refObj->Fields['dutyadmin'])) { $dutyadmin = $GLOBALS['cfg_df_dutyadmin']; - } - else - { + } else { $row = $dsql->GetOne("SELECT uname FROM `#@__admin` WHERE id='{$refObj->Fields['dutyadmin']}' "); $dutyadmin = isset($row['uname']) ? $row['uname'] : $GLOBALS['cfg_df_dutyadmin']; } return $dutyadmin; -} \ No newline at end of file +} diff --git a/include/taglib/arclist.lib.php b/include/taglib/arclist.lib.php index 82e0f5ab..cb885649 100755 --- a/include/taglib/arclist.lib.php +++ b/include/taglib/arclist.lib.php @@ -1,4 +1,4 @@ ->dede>> 文档列表 全局标记 @@ -31,30 +31,30 @@ {/dede:arclist} - col:分多少列显示(默认为单列),5.3版中本属性可以通过多种方式进行多行显示 - row:返回文档列表总数 - typeid:栏目ID,在列表模板和档案模板中一般不需要指定,在首页模板中允许用","分开表示多个栏目 - getall:在没有指定这属性的情况下,在栏目页、文章页模板,不会获取以","分开的多个栏目的下级子类 - titlelen:标题长度 等同于titlelength - infolen:表示内容简介长度 等同于infolength - imgwidth:缩略图宽度 - imgheight:缩略图高度 - listtype: 栏目类型 image含有缩略图 commend推荐 - orderby:文档排序方式 - keyword:含有指定关键字的文档列表,多个关键字用","分 - innertext:单条记录样式 - aid:指定文档ID - idlist:提取特定文档(文档ID - channelid:频道ID - limit:(起始ID从0开始)表示限定的记录范围(如:limit='1,2' 表示从ID为1的记录开始,取2条记录 - flag:自定义属性值:头条[h]推荐[c]图片[p]幻灯[f]滚动[s]跳转[j]图文[a]加粗[b] - noflag:同flag,但这里是表示不包含这些属性 - orderway:值为 desc 或 asc ,指定排序方式是降序还是顺向排序,默认为降序 - subday:表示在多少天以内的文档 - +col:分多少列显示(默认为单列),5.3版中本属性可以通过多种方式进行多行显示 +row:返回文档列表总数 +typeid:栏目ID,在列表模板和档案模板中一般不需要指定,在首页模板中允许用","分开表示多个栏目 +getall:在没有指定这属性的情况下,在栏目页、文章页模板,不会获取以","分开的多个栏目的下级子类 +titlelen:标题长度 等同于titlelength +infolen:表示内容简介长度 等同于infolength +imgwidth:缩略图宽度 +imgheight:缩略图高度 +listtype: 栏目类型 image含有缩略图 commend推荐 +orderby:文档排序方式 +keyword:含有指定关键字的文档列表,多个关键字用","分 +innertext:单条记录样式 +aid:指定文档ID +idlist:提取特定文档(文档ID +channelid:频道ID +limit:(起始ID从0开始)表示限定的记录范围(如:limit='1,2' 表示从ID为1的记录开始,取2条记录 +flag:自定义属性值:头条[h]推荐[c]图片[p]幻灯[f]滚动[s]跳转[j]图文[a]加粗[b] +noflag:同flag,但这里是表示不包含这些属性 +orderway:值为 desc 或 asc ,指定排序方式是降序还是顺向排序,默认为降序 +subday:表示在多少天以内的文档 + >>dede>>*/ -function lib_arclist( &$ctag, &$refObj ) +function lib_arclist(&$ctag, &$refObj) { global $envs; @@ -62,11 +62,10 @@ function lib_arclist( &$ctag, &$refObj ) $tagid = ''; $tagname = $ctag->GetTagName(); $channelid = $ctag->GetAtt('channelid'); - + //增加对分页内容的处理 $pagesize = $ctag->GetAtt('pagesize'); - if($pagesize == '') - { + if ($pagesize == '') { $multi = 0; } else { $tagid = $ctag->GetAtt('tagid'); @@ -74,66 +73,76 @@ function lib_arclist( &$ctag, &$refObj ) // arclist是否需要weight排序,默认为"N",如果需要排序则设置为"Y" $isweight = $ctag->GetAtt('isweight'); - if($tagname=='imglist' || $tagname=='imginfolist') { + if ($tagname == 'imglist' || $tagname == 'imginfolist') { $listtype = 'image'; - } - else if($tagname=='specart') { + } else if ($tagname == 'specart') { $channelid = -1; - $listtype=''; - } - else if($tagname=='coolart') { + $listtype = ''; + } else if ($tagname == 'coolart') { $listtype = 'commend'; - } - else if($tagname=='autolist') { + } else if ($tagname == 'autolist') { $autopartid = $ctag->GetAtt('partsort'); - } - else { + } else { $listtype = $ctag->GetAtt('type'); } //排序 - if($ctag->GetAtt('sort')!='') $orderby = $ctag->GetAtt('sort'); - else if($tagname=='hotart') $orderby = 'click'; - else $orderby = $ctag->GetAtt('orderby'); + if ($ctag->GetAtt('sort') != '') { + $orderby = $ctag->GetAtt('sort'); + } else if ($tagname == 'hotart') { + $orderby = 'click'; + } else { + $orderby = $ctag->GetAtt('orderby'); + } //对相应的标记使用不同的默认innertext - if(trim($ctag->GetInnerText()) != '') $innertext = $ctag->GetInnerText(); - else if($tagname=='imglist') $innertext = GetSysTemplets('part_imglist.htm'); - else if($tagname=='imginfolist') $innertext = GetSysTemplets('part_imginfolist.htm'); - else $innertext = GetSysTemplets("part_arclist.htm"); + if (trim($ctag->GetInnerText()) != '') { + $innertext = $ctag->GetInnerText(); + } else if ($tagname == 'imglist') { + $innertext = GetSysTemplets('part_imglist.htm'); + } else if ($tagname == 'imginfolist') { + $innertext = GetSysTemplets('part_imginfolist.htm'); + } else { + $innertext = GetSysTemplets("part_arclist.htm"); + } //兼容titlelength - if($ctag->GetAtt('titlelength')!='') $titlelen = $ctag->GetAtt('titlelength'); - else $titlelen = $ctag->GetAtt('titlelen'); + if ($ctag->GetAtt('titlelength') != '') { + $titlelen = $ctag->GetAtt('titlelength'); + } else { + $titlelen = $ctag->GetAtt('titlelen'); + } //兼容infolength - if($ctag->GetAtt('infolength')!='') $infolen = $ctag->GetAtt('infolength'); - else $infolen = $ctag->GetAtt('infolen'); + if ($ctag->GetAtt('infolength') != '') { + $infolen = $ctag->GetAtt('infolength'); + } else { + $infolen = $ctag->GetAtt('infolen'); + } $typeid = trim($ctag->GetAtt('typeid')); - if(empty($typeid)) { - $typeid = ( isset($refObj->Fields['typeid']) ? $refObj->Fields['typeid'] : $envs['typeid'] ); + if (empty($typeid)) { + $typeid = (isset($refObj->Fields['typeid']) ? $refObj->Fields['typeid'] : $envs['typeid']); } - if($listtype=='autolist') { - $typeid = lib_GetAutoChannelID($ctag->GetAtt('partsort'),$typeid); + if ($listtype == 'autolist') { + $typeid = lib_GetAutoChannelID($ctag->GetAtt('partsort'), $typeid); } - if($ctag->GetAtt('att')=='') { + if ($ctag->GetAtt('att') == '') { $flag = $ctag->GetAtt('flag'); - } - else { + } else { $flag = $ctag->GetAtt('att'); } return lib_arclistDone - ( - $refObj, $ctag, $typeid, $ctag->GetAtt('row'), $ctag->GetAtt('col'), $titlelen, $infolen, - $ctag->GetAtt('imgwidth'), $ctag->GetAtt('imgheight'), $listtype, $orderby, - $ctag->GetAtt('keyword'), $innertext, $envs['aid'], $ctag->GetAtt('idlist'), $channelid, - $ctag->GetAtt('limit'), $flag,$ctag->GetAtt('orderway'), $ctag->GetAtt('subday'), $ctag->GetAtt('noflag'), - $tagid,$pagesize,$isweight - ); + ( + $refObj, $ctag, $typeid, $ctag->GetAtt('row'), $ctag->GetAtt('col'), $titlelen, $infolen, + $ctag->GetAtt('imgwidth'), $ctag->GetAtt('imgheight'), $listtype, $orderby, + $ctag->GetAtt('keyword'), $innertext, $envs['aid'], $ctag->GetAtt('idlist'), $channelid, + $ctag->GetAtt('limit'), $flag, $ctag->GetAtt('orderway'), $ctag->GetAtt('subday'), $ctag->GetAtt('noflag'), + $tagid, $pagesize, $isweight + ); } /** @@ -165,23 +174,22 @@ function lib_arclist( &$ctag, &$refObj ) * @param string $isweight 是否需要对检索出来的内容按照weight排序 * @return string */ -function lib_arclistDone(&$refObj, &$ctag, $typeid=0, $row=10, $col=1, $titlelen=30, $infolen=160, - $imgwidth=120, $imgheight=90, $listtype='all', $orderby='default', $keyword='', - $innertext='', $arcid=0, $idlist='', $channelid=0, $limit='', $att='', $order='desc', $subday=0, $noflag='',$tagid='', $pagesize=0, $isweight='N') -{ - global $dsql,$PubFields,$cfg_keyword_like,$cfg_index_cache,$_arclistEnv,$envs,$cfg_cache_type,$cfg_digg_update; - $row = AttDef($row,10); - $titlelen = AttDef($titlelen,30); - $infolen = AttDef($infolen,160); - $imgwidth = AttDef($imgwidth,120); - $imgheight = AttDef($imgheight,120); - $listtype = AttDef($listtype,'all'); - $arcid = AttDef($arcid,0); - $channelid = AttDef($channelid,0); - $orderby = AttDef($orderby,'default'); - $orderWay = AttDef($order,'desc'); - $subday = AttDef($subday,0); - $pagesize = AttDef($pagesize,0); +function lib_arclistDone(&$refObj, &$ctag, $typeid = 0, $row = 10, $col = 1, $titlelen = 30, $infolen = 160, + $imgwidth = 120, $imgheight = 90, $listtype = 'all', $orderby = 'default', $keyword = '', + $innertext = '', $arcid = 0, $idlist = '', $channelid = 0, $limit = '', $att = '', $order = 'desc', $subday = 0, $noflag = '', $tagid = '', $pagesize = 0, $isweight = 'N') { + global $dsql, $PubFields, $cfg_keyword_like, $cfg_index_cache, $_arclistEnv, $envs, $cfg_cache_type, $cfg_digg_update; + $row = AttDef($row, 10); + $titlelen = AttDef($titlelen, 30); + $infolen = AttDef($infolen, 160); + $imgwidth = AttDef($imgwidth, 120); + $imgheight = AttDef($imgheight, 120); + $listtype = AttDef($listtype, 'all'); + $arcid = AttDef($arcid, 0); + $channelid = AttDef($channelid, 0); + $orderby = AttDef($orderby, 'default'); + $orderWay = AttDef($order, 'desc'); + $subday = AttDef($subday, 0); + $pagesize = AttDef($pagesize, 0); $line = $row; $orderby = strtolower($orderby); $keyword = trim($keyword); @@ -189,68 +197,91 @@ function lib_arclistDone(&$refObj, &$ctag, $typeid=0, $row=10, $col=1, $titlelen $tablewidth = $ctag->GetAtt('tablewidth'); $writer = $ctag->GetAtt('writer'); - if($tablewidth == "") $tablewidth = 100; - if(empty($col)) $col = 1; - $colWidth = ceil(100/$col); - $tablewidth = $tablewidth."%"; - $colWidth = $colWidth."%"; - + if ($tablewidth == "") { + $tablewidth = 100; + } + + if (empty($col)) { + $col = 1; + } + + $colWidth = ceil(100 / $col); + $tablewidth = $tablewidth . "%"; + $colWidth = $colWidth . "%"; + //记录属性,以便分页样式统一调用 $attarray = compact("row", "titlelen", 'infolen', 'imgwidth', 'imgheight', 'listtype', - 'arcid', 'channelid', 'orderby', 'orderWay', 'subday','pagesize', - 'orderby', 'keyword', 'tablewidth', 'col', 'colWidth'); + 'arcid', 'channelid', 'orderby', 'orderWay', 'subday', 'pagesize', + 'orderby', 'keyword', 'tablewidth', 'col', 'colWidth'); + + if ($innertext == '') { + $innertext = GetSysTemplets('part_arclist.htm'); + } + + if (@$ctag->GetAtt('getall') == 1) { + $getall = 1; + } else { + $getall = 0; + } - if($innertext=='') $innertext = GetSysTemplets('part_arclist.htm'); - if( @$ctag->GetAtt('getall') == 1 ) $getall = 1; - else $getall = 0; + if ($att == '0') { + $att = ''; + } + + if ($att == '3') { + $att = 'f'; + } - if($att=='0') $att=''; - if($att=='3') $att='f'; - if($att=='1') $att='h'; + if ($att == '1') { + $att = 'h'; + } $orwheres = array(); $maintable = '#@__archives'; //按不同情况设定SQL条件 排序方式 - if($idlist=='') - { - if($orderby=='near' && $cfg_keyword_like=='N') { $keyword=''; } + if ($idlist == '') { + if ($orderby == 'near' && $cfg_keyword_like == 'N') {$keyword = '';} - if($writer=='this') { - $wmid = isset($refObj->Fields['mid']) ? $refObj->Fields['mid'] : 0; + if ($writer == 'this') { + $wmid = isset($refObj->Fields['mid']) ? $refObj->Fields['mid'] : 0; $orwheres[] = " arc.mid = '$wmid' "; } - + //时间限制(用于调用最近热门文章、热门评论之类),这里的时间只能计算到天,否则缓存功能将无效 - if($subday > 0) - { + if ($subday > 0) { $ntime = gmmktime(0, 0, 0, gmdate('m'), gmdate('d'), gmdate('Y')); $limitday = $ntime - ($subday * 24 * 3600); $orwheres[] = " arc.senddate > $limitday "; } //关键字条件 - if($keyword!='') - { + if ($keyword != '') { $keyword = str_replace(',', '|', $keyword); $orwheres[] = " CONCAT(arc.title,arc.keywords) REGEXP '$keyword' "; } //文档属性 - if(preg_match('/commend/i', $listtype)) $orwheres[] = " FIND_IN_SET('c', arc.flag)>0 "; - if(preg_match('/image/i', $listtype)) $orwheres[] = " FIND_IN_SET('p', arc.flag)>0 "; - if($att != '') { + if (preg_match('/commend/i', $listtype)) { + $orwheres[] = " FIND_IN_SET('c', arc.flag)>0 "; + } + + if (preg_match('/image/i', $listtype)) { + $orwheres[] = " FIND_IN_SET('p', arc.flag)>0 "; + } + + if ($att != '') { $flags = explode(',', $att); - for($i=0; isset($flags[$i]); $i++) $orwheres[] = " FIND_IN_SET('{$flags[$i]}', arc.flag)>0 "; + for ($i = 0;isset($flags[$i]); $i++) { + $orwheres[] = " FIND_IN_SET('{$flags[$i]}', arc.flag)>0 "; + } + } - if(!empty($typeid) && $typeid != 'top') - { + if (!empty($typeid) && $typeid != 'top') { //指定了多个栏目时,不再获取子类的id - if( preg_match('#,#', $typeid) ) - { + if (preg_match('#,#', $typeid)) { //指定了getall属性或主页模板例外 - if($getall==1 || empty($refObj->Fields['typeid'])) - { + if ($getall == 1 || empty($refObj->Fields['typeid'])) { $typeids = explode(',', $typeid); - foreach($typeids as $ttid) { + foreach ($typeids as $ttid) { $typeidss[] = GetSonIds($ttid); } $typeidStr = join(',', $typeidss); @@ -259,60 +290,61 @@ function lib_arclistDone(&$refObj, &$ctag, $typeid=0, $row=10, $col=1, $titlelen $typeid = join(',', $typeidssok); } $orwheres[] = " arc.typeid IN ($typeid) "; - } - else - { + } else { //处理交叉栏目 $CrossID = ''; - if($ctag->GetAtt('cross')=='1') - { + if ($ctag->GetAtt('cross') == '1') { $arr = $dsql->GetOne("SELECT `id`,`topid`,`cross`,`crossid`,`ispart`,`typename` FROM `#@__arctype` WHERE id='$typeid' "); - if( $arr['cross']==0 || ( $arr['cross']==2 && trim($arr['crossid']=='') ) ) - { - $orwheres[] = ' arc.typeid IN ('.GetSonIds($typeid).')'; - } - else - { + if ($arr['cross'] == 0 || ($arr['cross'] == 2 && trim($arr['crossid'] == ''))) { + $orwheres[] = ' arc.typeid IN (' . GetSonIds($typeid) . ')'; + } else { $selquery = ''; - if($arr['cross']==1) { + if ($arr['cross'] == 1) { $selquery = "SELECT id,topid FROM `#@__arctype` WHERE typename LIKE '{$arr['typename']}' AND id<>'{$typeid}' AND topid<>'{$typeid}' "; - } - else { + } else { $arr['crossid'] = preg_replace('#[^0-9,]#', '', trim($arr['crossid'])); - if($arr['crossid']!='') $selquery = "SELECT id,topid FROM `#@__arctype` WHERE id IN('{$arr['crossid']}') AND id<>'{$typeid}' AND topid<>'{$typeid}' "; + if ($arr['crossid'] != '') { + $selquery = "SELECT id,topid FROM `#@__arctype` WHERE id IN('{$arr['crossid']}') AND id<>'{$typeid}' AND topid<>'{$typeid}' "; + } + } - if($selquery!='') - { + if ($selquery != '') { $dsql->SetQuery($selquery); $dsql->Execute(); - while($arr = $dsql->GetArray()) - { - $CrossID .= ($CrossID=='' ? $arr['id'] : ','.$arr['id']); + while ($arr = $dsql->GetArray()) { + $CrossID .= ($CrossID == '' ? $arr['id'] : ',' . $arr['id']); } } } } - if($CrossID=='') $orwheres[] = ' arc.typeid IN ('.GetSonIds($typeid).')'; - else $orwheres[] = ' arc.typeid IN ('.GetSonIds($typeid).','.$CrossID.')'; + if ($CrossID == '') { + $orwheres[] = ' arc.typeid IN (' . GetSonIds($typeid) . ')'; + } else { + $orwheres[] = ' arc.typeid IN (' . GetSonIds($typeid) . ',' . $CrossID . ')'; + } + } } //频道ID - if(preg_match('#spec#i', $listtype)) $channelid==-1; + if (preg_match('#spec#i', $listtype)) { + $channelid == -1; + } - if(!empty($channelid)) $orwheres[] = " And arc.channel = '$channelid' "; + if (!empty($channelid)) { + $orwheres[] = " And arc.channel = '$channelid' "; + } - if(!empty($noflag)) - { - if(!preg_match('#,#', $noflag)) - { + if (!empty($noflag)) { + if (!preg_match('#,#', $noflag)) { $orwheres[] = " FIND_IN_SET('$noflag', arc.flag)<1 "; - } - else - { + } else { $noflags = explode(',', $noflag); - foreach($noflags as $noflag) { - if(trim($noflag)=='') continue; + foreach ($noflags as $noflag) { + if (trim($noflag) == '') { + continue; + } + $orwheres[] = " FIND_IN_SET('$noflag', arc.flag)<1 "; } } @@ -326,49 +358,62 @@ function lib_arclistDone(&$refObj, &$ctag, $typeid=0, $row=10, $col=1, $titlelen //文档排序的方式 $ordersql = ''; - if($orderby=='hot' || $orderby=='click') $ordersql = " ORDER BY arc.click $orderWay"; - else if($orderby == 'sortrank' || $orderby=='pubdate') $ordersql = " ORDER BY arc.sortrank $orderWay"; - else if($orderby == 'id') $ordersql = " ORDER BY arc.id $orderWay"; - else if($orderby == 'near') $ordersql = " ORDER BY ABS(arc.id - ".$arcid.")"; - else if($orderby == 'lastpost') $ordersql = " ORDER BY arc.lastpost $orderWay"; - else if($orderby == 'scores') $ordersql = " ORDER BY arc.scores $orderWay"; + if ($orderby == 'hot' || $orderby == 'click') { + $ordersql = " ORDER BY arc.click $orderWay"; + } else if ($orderby == 'sortrank' || $orderby == 'pubdate') { + $ordersql = " ORDER BY arc.sortrank $orderWay"; + } else if ($orderby == 'id') { + $ordersql = " ORDER BY arc.id $orderWay"; + } else if ($orderby == 'near') { + $ordersql = " ORDER BY ABS(arc.id - " . $arcid . ")"; + } else if ($orderby == 'lastpost') { + $ordersql = " ORDER BY arc.lastpost $orderWay"; + } else if ($orderby == 'scores') { + $ordersql = " ORDER BY arc.scores $orderWay"; + } + //功能:增加按好评数和差评数调用 - else if($orderby == 'goodpost') $ordersql = " order by arc.goodpost $orderWay"; - else if($orderby == 'badpost') $ordersql = " order by arc.badpost $orderWay"; - else if($orderby == 'rand') $ordersql = " ORDER BY rand()"; - else $ordersql = " ORDER BY arc.sortrank $orderWay"; + else if ($orderby == 'goodpost') { + $ordersql = " order by arc.goodpost $orderWay"; + } else if ($orderby == 'badpost') { + $ordersql = " order by arc.badpost $orderWay"; + } else if ($orderby == 'rand') { + $ordersql = " ORDER BY rand()"; + } else { + $ordersql = " ORDER BY arc.sortrank $orderWay"; + } //limit条件 $limit = trim(preg_replace('#limit#is', '', $limit)); - if($limit!='') - { + if ($limit != '') { $limitsql = " LIMIT $limit "; $limitarr = explode(',', $limit); - $line = isset($limitarr[1])? $limitarr[1] : $line; + $line = isset($limitarr[1]) ? $limitarr[1] : $line; + } else { + $limitsql = " LIMIT 0,$line "; } - else $limitsql = " LIMIT 0,$line "; - + $orwhere = ''; - if(isset($orwheres[0])) { - $orwhere = join(' And ',$orwheres); + if (isset($orwheres[0])) { + $orwhere = join(' And ', $orwheres); $orwhere = preg_replace("#^ And#is", '', $orwhere); $orwhere = preg_replace("#And[ ]{1,}And#is", 'And ', $orwhere); } - if($orwhere!='') $orwhere = " WHERE $orwhere "; - + if ($orwhere != '') { + $orwhere = " WHERE $orwhere "; + } + //获取附加表信息 $addfield = trim($ctag->GetAtt('addfields')); $addfieldsSql = ''; $addfieldsSqlJoin = ''; - if($addfield != '' && !empty($channelid)) - { + if ($addfield != '' && !empty($channelid)) { $row = $dsql->GetOne("SELECT addtable FROM `#@__channeltype` WHERE id='$channelid' "); - if(isset($row['addtable']) && trim($row['addtable']) != '') - { + if (isset($row['addtable']) && trim($row['addtable']) != '') { $addtable = trim($row['addtable']); $addfields = explode(',', $addfield); $row['addtable'] = trim($row['addtable']); - $addfieldsSql = ",addf.".join(',addf.', $addfields); + $addfieldsSql = ",addf." . join(',addf.', $addfields); $addfieldsSqlJoin = " LEFT JOIN `$addtable` addf ON addf.aid = arc.id "; } } @@ -381,32 +426,29 @@ function lib_arclistDone(&$refObj, &$ctag, $typeid=0, $row=10, $col=1, $titlelen $orwhere $ordersql $limitsql"; //统一hash - $taghash = md5(serialize($ctag).$typeid); + $taghash = md5(serialize($ctag) . $typeid); $needSaveCache = true; //进行tagid的默认处理 - if($pagesize > 0) $tagid = AttDef($tagid,'tag'.$taghash ); - - if($idlist!='' || $GLOBALS['_arclistEnv']=='index' || $cfg_index_cache==0) - { - $needSaveCache = false; + if ($pagesize > 0) { + $tagid = AttDef($tagid, 'tag' . $taghash); } - else - { + + if ($idlist != '' || $GLOBALS['_arclistEnv'] == 'index' || $cfg_index_cache == 0) { + $needSaveCache = false; + } else { $idlist = GetArclistCache($taghash); - if($idlist != '') { + if ($idlist != '') { $needSaveCache = false; } //如果使用的是内容缓存,直接返回结果 - if($cfg_cache_type=='content' && $idlist != '') - { - $idlist = ($idlist==0 ? '' : $idlist); + if ($cfg_cache_type == 'content' && $idlist != '') { + $idlist = ($idlist == 0 ? '' : $idlist); return $idlist; } } //指定了id或使用缓存中的id - if($idlist != '') - { + if ($idlist != '') { $query = "SELECT arc.*,tp.typedir,tp.typename,tp.corank,tp.isdefault,tp.defaultname,tp.namerule,tp.namerule2,tp.ispart, tp.moresite,tp.siteurl,tp.sitepath $addfieldsSql @@ -414,193 +456,206 @@ function lib_arclistDone(&$refObj, &$ctag, $typeid=0, $row=10, $col=1, $titlelen $addfieldsSqlJoin WHERE arc.id in($idlist) $ordersql "; } - - // 好评差评缓存更新 - if($cfg_digg_update > 0) - { - if($orderby == 'goodpost' || $orderby == 'badpost') - { - $t1 = ExecTime(); - $postsql = "SELECT arc.id,arc.goodpost,arc.badpost,arc.scores + + // 好评差评缓存更新 + if ($cfg_digg_update > 0) { + if ($orderby == 'goodpost' || $orderby == 'badpost') { + $t1 = ExecTime(); + $postsql = "SELECT arc.id,arc.goodpost,arc.badpost,arc.scores FROM `$maintable` arc $orwhere $ordersql $limitsql"; - - if($idlist != '') - { - $postsql = "SELECT arc.id,arc.goodpost,arc.badpost,arc.scores - FROM `$maintable` arc + + if ($idlist != '') { + $postsql = "SELECT arc.id,arc.goodpost,arc.badpost,arc.scores + FROM `$maintable` arc WHERE arc.id in($idlist) $ordersql "; - } - $dsql->SetQuery($query); - $dsql->Execute('lit'); - while ($row = $dsql->GetArray('lit')) { - $prefix = 'diggCache'; - $key = 'aid-'.$row['id']; - $cacherow = GetCache($prefix, $key); - $setsql = array(); - if(!empty($cacherow['scores']) && $cacherow['scores'] != $row['scores']) - { - $setsql[] = "scores = {$cacherow['scores']}"; - } - if(!empty($cacherow['goodpost']) && $cacherow['goodpost'] != $row['goodpost']) - { - $setsql[] = "goodpost = {$cacherow['goodpost']}"; - } - if(!empty($cacherow['badpost']) && $cacherow['badpost'] != $row['badpost']) - { - $setsql[] = "badpost = {$cacherow['badpost']}"; - } - $setsql = implode(',', $setsql); - $sql = "UPDATE `$maintable` SET {$setsql} WHERE id='{$row['id']}'"; - if(!empty($setsql)) - { - $dsql->ExecuteNoneQuery($sql); - } - } - //echo ExecTime()-$t1; - } - } - + } + $dsql->SetQuery($query); + $dsql->Execute('lit'); + while ($row = $dsql->GetArray('lit')) { + $prefix = 'diggCache'; + $key = 'aid-' . $row['id']; + $cacherow = GetCache($prefix, $key); + $setsql = array(); + if (!empty($cacherow['scores']) && $cacherow['scores'] != $row['scores']) { + $setsql[] = "scores = {$cacherow['scores']}"; + } + if (!empty($cacherow['goodpost']) && $cacherow['goodpost'] != $row['goodpost']) { + $setsql[] = "goodpost = {$cacherow['goodpost']}"; + } + if (!empty($cacherow['badpost']) && $cacherow['badpost'] != $row['badpost']) { + $setsql[] = "badpost = {$cacherow['badpost']}"; + } + $setsql = implode(',', $setsql); + $sql = "UPDATE `$maintable` SET {$setsql} WHERE id='{$row['id']}'"; + if (!empty($setsql)) { + $dsql->ExecuteNoneQuery($sql); + } + } + //echo ExecTime()-$t1; + } + } + $dsql->SetQuery($query); $dsql->Execute('al'); //$row = $dsql->GetArray("al"); $artlist = ''; - if($pagesize > 0) $artlist .= "
\r\n"; - if($col > 1) $artlist = "\r\n"; + if ($pagesize > 0) { + $artlist .= "
\r\n"; + } + + if ($col > 1) { + $artlist = "
\r\n"; + } + $dtp2 = new DedeTagParse(); $dtp2->SetNameSpace('field', '[', ']'); $dtp2->LoadString($innertext); $GLOBALS['autoindex'] = 0; $ids = array(); $orderWeight = array(); - - for($i=0; $i<$line; $i++) - { - if($col>1) $artlist .= "\r\n"; - for($j=0; $j<$col; $j++) - { - if($col>1) $artlist .= " \r\n"; + } + + for ($j = 0; $j < $col; $j++) { + if ($col > 1) { + $artlist .= " \r\n"; - }//Loop Col - if($col>1) $i += $col - 1; - if($col>1) $artlist .= " \r\n"; - }//loop line - if($col>1) $artlist .= "
\r\n"; - if($row = $dsql->GetArray("al")) - { + + for ($i = 0; $i < $line; $i++) { + if ($col > 1) { + $artlist .= "
\r\n"; + } + + if ($row = $dsql->GetArray("al")) { $ids[] = $row['id']; //处理一些特殊字段 - $row['info'] = $row['infos'] = cn_substr($row['description'],$infolen); - $row['id'] = $row['id']; + $row['info'] = $row['infos'] = cn_substr($row['description'], $infolen); + $row['id'] = $row['id']; - if($row['corank'] > 0 && $row['arcrank']==0) - { + if ($row['corank'] > 0 && $row['arcrank'] == 0) { $row['arcrank'] = $row['corank']; } - $row['filename'] = $row['arcurl'] = GetFileUrl($row['id'],$row['typeid'],$row['senddate'],$row['title'],$row['ismake'], - $row['arcrank'],$row['namerule'],$row['typedir'],$row['money'],$row['filename'],$row['moresite'],$row['siteurl'],$row['sitepath']); + $row['filename'] = $row['arcurl'] = GetFileUrl($row['id'], $row['typeid'], $row['senddate'], $row['title'], $row['ismake'], + $row['arcrank'], $row['namerule'], $row['typedir'], $row['money'], $row['filename'], $row['moresite'], $row['siteurl'], $row['sitepath']); - $row['typeurl'] = GetTypeUrl($row['typeid'],$row['typedir'],$row['isdefault'],$row['defaultname'],$row['ispart'], - $row['namerule2'],$row['moresite'],$row['siteurl'],$row['sitepath']); + $row['typeurl'] = GetTypeUrl($row['typeid'], $row['typedir'], $row['isdefault'], $row['defaultname'], $row['ispart'], + $row['namerule2'], $row['moresite'], $row['siteurl'], $row['sitepath']); - if($row['litpic'] == '-' || $row['litpic'] == '') - { - $row['litpic'] = $GLOBALS['cfg_cmspath'].'/resources/img/defaultpic.gif'; + if ($row['litpic'] == '-' || $row['litpic'] == '') { + $row['litpic'] = $GLOBALS['cfg_cmspath'] . '/resources/img/defaultpic.gif'; } - if(!preg_match("#^http:\/\/#i", $row['litpic']) && $GLOBALS['cfg_multi_site'] == 'Y') - { - $row['litpic'] = $GLOBALS['cfg_mainsite'].$row['litpic']; + if (!preg_match("#^http:\/\/#i", $row['litpic']) && $GLOBALS['cfg_multi_site'] == 'Y') { + $row['litpic'] = $GLOBALS['cfg_mainsite'] . $row['litpic']; } $row['picname'] = $row['litpic']; $row['stime'] = GetDateMK($row['pubdate']); - $row['typelink'] = "".$row['typename'].""; - $row['image'] = "".preg_replace("#[<]#", "", $row['title'])."'>"; - $row['imglink'] = "".$row['image'].""; + $row['typelink'] = "" . $row['typename'] . ""; + $row['image'] = "" . preg_replace("#[<]#", "", $row['title']) . "'>"; + $row['imglink'] = "" . $row['image'] . ""; $row['fulltitle'] = $row['title']; $row['title'] = cn_substr($row['title'], $titlelen); - if($row['color']!='') $row['title'] = "".$row['title'].""; - if(preg_match('#b#', $row['flag'])) $row['title'] = "".$row['title'].""; + if ($row['color'] != '') { + $row['title'] = "" . $row['title'] . ""; + } + + if (preg_match('#b#', $row['flag'])) { + $row['title'] = "" . $row['title'] . ""; + } + //$row['title'] = "".$row['title'].""; - $row['textlink'] = "".$row['title'].""; + $row['textlink'] = "" . $row['title'] . ""; $row['plusurl'] = $row['phpurl'] = $GLOBALS['cfg_phpurl']; $row['memberurl'] = $GLOBALS['cfg_memberurl']; $row['templeturl'] = $GLOBALS['cfg_templeturl']; - if(is_array($dtp2->CTags)) - { - foreach($dtp2->CTags as $k=>$ctag) - { - if($ctag->GetName()=='array') - { + if (is_array($dtp2->CTags)) { + foreach ($dtp2->CTags as $k => $ctag) { + if ($ctag->GetName() == 'array') { //传递整个数组,在runphp模式中有特殊作用 $dtp2->Assign($k, $row); } else { - if(isset($row[$ctag->GetName()])) $dtp2->Assign($k,$row[$ctag->GetName()]); - else $dtp2->Assign($k, ''); + if (isset($row[$ctag->GetName()])) { + $dtp2->Assign($k, $row[$ctag->GetName()]); + } else { + $dtp2->Assign($k, ''); + } + } } $GLOBALS['autoindex']++; } - if($pagesize > 0) - { - if($GLOBALS['autoindex'] <= $pagesize) - { + if ($pagesize > 0) { + if ($GLOBALS['autoindex'] <= $pagesize) { $liststr = $dtp2->GetResult(); - $artlist .= $liststr."\r\n"; + $artlist .= $liststr . "\r\n"; } else { $artlist .= ""; $orderWeight[] = array( - 'weight' => $row['weight'], - 'arclist' => '' + 'weight' => $row['weight'], + 'arclist' => '', ); } } else { $liststr = $dtp2->GetResult(); - $artlist .= $liststr."\r\n"; + $artlist .= $liststr . "\r\n"; } $orderWeight[] = array( - 'weight' => $row['weight'], - 'arclist' => $liststr + 'weight' => $row['weight'], + 'arclist' => $liststr, ); - }//if hasRow - else{ + } //if hasRow + else { $artlist .= ''; } - + // 进行判断,如果启用排序则内容输出为重新排序后的内容 // var_dump($isweight=='y' && count($orderWeight) == $line); $isweight = strtolower($isweight); - if ( $isweight=='y' ) - { + if ($isweight == 'y') { $artlist = ''; $orderWeight = list_sort_by($orderWeight, 'weight', 'asc'); - + foreach ($orderWeight as $vv) { - $artlist .= $vv['arclist']; + $artlist .= $vv['arclist']; } } - if($col>1) $artlist .= "
\r\n"; + if ($col > 1) { + $artlist .= " \r\n"; + } + + } //Loop Col + if ($col > 1) { + $i += $col - 1; + } + + if ($col > 1) { + $artlist .= " \r\n"; + } + + } //loop line + if ($col > 1) { + $artlist .= " \r\n"; + } + $dsql->FreeResult("al"); $idsstr = join(',', $ids); - + //分页特殊处理 - if($pagesize > 0) - { + if ($pagesize > 0) { $artlist .= "
\r\n"; - $row = $dsql->GetOne("SELECT tagid FROM #@__arcmulti WHERE tagid='$tagid'"); - $uptime = time(); - $attstr = addslashes(serialize($attarray)); - $innertext = addslashes($innertext); - if(!is_array($row)) - { - $query = " + $row = $dsql->GetOne("SELECT tagid FROM #@__arcmulti WHERE tagid='$tagid'"); + $uptime = time(); + $attstr = addslashes(serialize($attarray)); + $innertext = addslashes($innertext); + if (!is_array($row)) { + $query = " INSERT INTO #@__arcmulti(tagid,uptime,innertext,pagesize,arcids,ordersql,addfieldsSql,addfieldsSqlJoin,attstr) VALUES('$tagid','$uptime','$innertext','$pagesize','$idsstr','$ordersql','$addfieldsSql','$addfieldsSqlJoin','$attstr'); "; - $dsql->ExecuteNoneQuery($query); - } else { - $query = "UPDATE `#@__arcmulti` + $dsql->ExecuteNoneQuery($query); + } else { + $query = "UPDATE `#@__arcmulti` SET uptime='$uptime', innertext='$innertext', @@ -612,19 +667,21 @@ function lib_arclistDone(&$refObj, &$ctag, $typeid=0, $row=10, $col=1, $titlelen attstr='$attstr' WHERE tagid='$tagid' "; - $dsql->ExecuteNoneQuery($query); - } + $dsql->ExecuteNoneQuery($query); + } } - + //保存ID缓存 - if($needSaveCache) - { - if($idsstr=='') $idsstr = '0'; - if($cfg_cache_type=='content' && $idsstr!='0') { + if ($needSaveCache) { + if ($idsstr == '') { + $idsstr = '0'; + } + + if ($cfg_cache_type == 'content' && $idsstr != '0') { $idsstr = addslashes($artlist); } - $inquery = "INSERT INTO `#@__arccache`(`md5hash`,`uptime`,`cachedata`) VALUES ('".$taghash."','".time()."', '$idsstr'); "; - $dsql->ExecuteNoneQuery("DELETE FROM `#@__arccache` WHERE md5hash='".$taghash."' "); + $inquery = "INSERT INTO `#@__arccache`(`md5hash`,`uptime`,`cachedata`) VALUES ('" . $taghash . "','" . time() . "', '$idsstr'); "; + $dsql->ExecuteNoneQuery("DELETE FROM `#@__arccache` WHERE md5hash='" . $taghash . "' "); $dsql->ExecuteNoneQuery($inquery); } return $artlist; @@ -639,18 +696,22 @@ function lib_arclistDone(&$refObj, &$ctag, $typeid=0, $row=10, $col=1, $titlelen */ function GetArclistCache($md5hash) { - global $dsql,$envs,$cfg_makesign_cache,$cfg_index_cache,$cfg_cache_type; - if($cfg_index_cache <= 0) return ''; - if(isset($envs['makesign']) && $cfg_makesign_cache=='N') return ''; - $mintime = time() - $cfg_index_cache; - $arr = $dsql->GetOne("SELECT cachedata,uptime FROM `#@__arccache` WHERE md5hash = '$md5hash' "); - if(!is_array($arr)) { + global $dsql, $envs, $cfg_makesign_cache, $cfg_index_cache, $cfg_cache_type; + if ($cfg_index_cache <= 0) { return ''; } - else if($arr['uptime'] < $mintime) { + + if (isset($envs['makesign']) && $cfg_makesign_cache == 'N') { return ''; } - else { + + $mintime = time() - $cfg_index_cache; + $arr = $dsql->GetOne("SELECT cachedata,uptime FROM `#@__arccache` WHERE md5hash = '$md5hash' "); + if (!is_array($arr)) { + return ''; + } else if ($arr['uptime'] < $mintime) { + return ''; + } else { return $arr['cachedata']; } } @@ -659,18 +720,25 @@ function GetArclistCache($md5hash) * 获取自动频道ID * * @access public - * @param string $sortid + * @param string $sortid * @param string $topid * @return string */ function lib_GetAutoChannelID($sortid, $topid) { global $dsql; - if(empty($sortid)) $sortid = 1; + if (empty($sortid)) { + $sortid = 1; + } + $getstart = $sortid - 1; $row = $dsql->GetOne("SELECT id,typename FROM #@__arctype WHERE reid='{$topid}' And ispart<2 And ishidden<>'1' ORDER BY sortrank asc limit $getstart,1"); - if(!is_array($row)) return 0; - else return $row['id']; + if (!is_array($row)) { + return 0; + } else { + return $row['id']; + } + } /** @@ -683,25 +751,30 @@ function lib_GetAutoChannelID($sortid, $topid) * asc正向排序 desc逆向排序 nat自然排序 * @return array */ -function list_sort_by($list, $field, $sortby='asc') { - if(is_array($list)){ - $refer = $resultSet = array(); - foreach ($list as $i => $data) - $refer[$i] = &$data[$field]; - switch ($sortby) { - case 'asc': // 正向排序 +function list_sort_by($list, $field, $sortby = 'asc') +{ + if (is_array($list)) { + $refer = $resultSet = array(); + foreach ($list as $i => $data) { + $refer[$i] = &$data[$field]; + } + + switch ($sortby) { + case 'asc': // 正向排序 asort($refer); break; - case 'desc':// 逆向排序 + case 'desc': // 逆向排序 arsort($refer); break; - case 'nat': // 自然排序 + case 'nat': // 自然排序 natcasesort($refer); break; - } - foreach ( $refer as $key=> $val) - $resultSet[] = &$list[$key]; - return $resultSet; - } - return false; -} \ No newline at end of file + } + foreach ($refer as $key => $val) { + $resultSet[] = &$list[$key]; + } + + return $resultSet; + } + return false; +} diff --git a/include/taglib/arclistsg.lib.php b/include/taglib/arclistsg.lib.php index 7817866a..9d24dff3 100755 --- a/include/taglib/arclistsg.lib.php +++ b/include/taglib/arclistsg.lib.php @@ -9,7 +9,7 @@ * @link http://www.dedecms.com */ - /** +/** * arclistsg解析标签 * * @access public @@ -17,172 +17,201 @@ * @param object $refObj 引用对象 * @return string 成功后返回解析后的标签内容 */ - + /*>>dede>> 独立单表模型列表 全局标记 V55,V56,V57 单表独立模型的文档列表调用标记 -{dede:arclistsg flag='h' typeid='' row='' col='' titlelen='' orderway='' keyword='' limit='0,1'} -[field:title/] +{dede:arclistsg flag='h' typeid='' row='' col='' titlelen='' orderway='' keyword='' limit='0,1'} +[field:title/] {/dede:arclistsg} - row:返回文档列表总数 - typeid:栏目ID,在列表模板和档案模板中一般不需要指定,在封面模板中允许用","分开表示多个栏目 - titlelen:标题长度 等同于titlelength - orderwey:排序方向 - keyword:含有指定关键字的文档列表,多个关键字用","分 - innertext:单条记录样式(innertext是放在标签之间的代码) - arcid:指定文档ID - idlist:提取特定文档(文档ID) - channelid: 频道ID - limit:表示限定的记录范围 - flag:自定义属性值:头条[h]推荐[c]图片[p]幻灯[f]滚动[s]跳转[j]图文[a]加粗[b] - subday:表示在多少天以内的文档 - +row:返回文档列表总数 +typeid:栏目ID,在列表模板和档案模板中一般不需要指定,在封面模板中允许用","分开表示多个栏目 +titlelen:标题长度 等同于titlelength +orderwey:排序方向 +keyword:含有指定关键字的文档列表,多个关键字用","分 +innertext:单条记录样式(innertext是放在标签之间的代码) +arcid:指定文档ID +idlist:提取特定文档(文档ID) +channelid: 频道ID +limit:表示限定的记录范围 +flag:自定义属性值:头条[h]推荐[c]图片[p]幻灯[f]滚动[s]跳转[j]图文[a]加粗[b] +subday:表示在多少天以内的文档 + >>dede>>*/ -function lib_arclistsg(&$ctag,&$refObj) +function lib_arclistsg(&$ctag, &$refObj) { - global $dsql,$PubFields,$cfg_keyword_like,$cfg_index_cache,$_arclistEnv,$envs,$_sys_globals; + global $dsql, $PubFields, $cfg_keyword_like, $cfg_index_cache, $_arclistEnv, $envs, $_sys_globals; //属性处理 - $attlist="typeid|0,row|10,col|1,flag|,titlelen|30,sort|default,keyword|,innertext|,arcid|0,idlist|,channelid|0,limit|,orderway|desc,subday|0"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "typeid|0,row|10,col|1,flag|,titlelen|30,sort|default,keyword|,innertext|,arcid|0,idlist|,channelid|0,limit|,orderway|desc,subday|0"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $line = $row; - $orderby=strtolower($sort); - if($col=='') $col = 1; - if(empty($imgwidth)) $imgwidth = ""; - if(empty($imgheight)) $imgheight = ""; + $orderby = strtolower($sort); + if ($col == '') { + $col = 1; + } + + if (empty($imgwidth)) { + $imgwidth = ""; + } + + if (empty($imgheight)) { + $imgheight = ""; + } + $innertext = trim($ctag->GetInnerText()); - if($innertext=='') $innertext = GetSysTemplets("part_arclistsg.htm"); + if ($innertext == '') { + $innertext = GetSysTemplets("part_arclistsg.htm"); + } - if(empty($channelid) && isset($GLOBALS['envs']['channelid'])) { + if (empty($channelid) && isset($GLOBALS['envs']['channelid'])) { $channelid = $GLOBALS['envs']['channelid']; } - - if(empty($typeid) && !empty($envs['typeid'])) { - $typeid = $envs['typeid']; + + if (empty($typeid) && !empty($envs['typeid'])) { + $typeid = $envs['typeid']; } - - if(empty($typeid) && empty($channelid)) - { + + if (empty($typeid) && empty($channelid)) { return "No channel info!"; } - if(!empty($channelid)) $gquery = "SELECT addtable,listfields FROM `#@__channeltype` WHERE id='$channelid' "; - else $gquery = "SELECT ch.addtable,listfields FROM `#@__arctype` tp LEFT JOIN `#@__channeltype` ch ON ch.id=tp.channeltype WHERE id='$typeid'"; + if (!empty($channelid)) { + $gquery = "SELECT addtable,listfields FROM `#@__channeltype` WHERE id='$channelid' "; + } else { + $gquery = "SELECT ch.addtable,listfields FROM `#@__arctype` tp LEFT JOIN `#@__channeltype` ch ON ch.id=tp.channeltype WHERE id='$typeid'"; + } - $row = $dsql->GetOne($gquery); + $row = $dsql->GetOne($gquery); $orwheres = array(); $maintable = trim($row['addtable']); - if($maintable=='') - { + if ($maintable == '') { return "No addtable info!"; } //列表调用字段 $listarcs = array('aid', 'typeid'); - if(!empty($row['listfields'])) - { - $listfields = explode(',', $row['listfields']); - foreach($listfields as $v) - { - if(!in_array($v, $listarcs)) $listarcs[] = $v; - } + if (!empty($row['listfields'])) { + $listfields = explode(',', $row['listfields']); + foreach ($listfields as $v) { + if (!in_array($v, $listarcs)) { + $listarcs[] = $v; + } + + } } $arclistquery = join(',', $listarcs); $arclistquery .= ",arc.aid AS id,arc.senddate AS pubdate"; //按不同情况设定SQL条件 排序方式 - if($idlist=='') - { - if($orderby=='near' && $cfg_keyword_like=='N'){ $keyword=''; } + if ($idlist == '') { + if ($orderby == 'near' && $cfg_keyword_like == 'N') {$keyword = '';} //时间限制(用于调用最近热门文章、热门评论之类) - if($subday>0) - { + if ($subday > 0) { //这里的时间只能计算到天,否则缓存功能将无效 $ntime = gmmktime(0, 0, 0, gmdate('m'), gmdate('d'), gmdate('Y')); $limitday = $ntime - ($subday * 24 * 3600); $orwheres[] = " arc.senddate > $limitday "; } - - if($flag!='') - { - $flags = explode(',',$flag); - for($i=0;isset($flags[$i]);$i++) $orwheres[] = " FIND_IN_SET('{$flags[$i]}',flag)>0 "; + + if ($flag != '') { + $flags = explode(',', $flag); + for ($i = 0;isset($flags[$i]); $i++) { + $orwheres[] = " FIND_IN_SET('{$flags[$i]}',flag)>0 "; + } + } - if(!empty($typeid)) - { + if (!empty($typeid)) { //指定了多个栏目时,不再获取子类的id - if(preg_match('#,#',$typeid)) $orwheres[] = " typeid IN ($typeid) "; - else - { + if (preg_match('#,#', $typeid)) { + $orwheres[] = " typeid IN ($typeid) "; + } else { //处理交叉栏目 $CrossID = ''; - if((isset($envs['cross']) || $ctag->GetAtt('cross')=='1' ) && $ctag->GetAtt('nocross')!='1') - { + if ((isset($envs['cross']) || $ctag->GetAtt('cross') == '1') && $ctag->GetAtt('nocross') != '1') { $arr = $dsql->GetOne("SELECT `id`,`topid`,`cross`,`crossid`,`ispart`,`typename` FROM `#@__arctype` WHERE id='$typeid' "); - if($arr['cross']==0 || ($arr['cross']==2 && trim($arr['crossid']==''))) - $orwheres[] = ' typeid IN ('.GetSonIds($typeid).')'; - else - { + if ($arr['cross'] == 0 || ($arr['cross'] == 2 && trim($arr['crossid'] == ''))) { + $orwheres[] = ' typeid IN (' . GetSonIds($typeid) . ')'; + } else { $selquery = ''; - if($arr['cross']==1) { + if ($arr['cross'] == 1) { $selquery = "SELECT id,topid FROM `#@__arctype` WHERE typename like '{$arr['typename']}' AND id<>'{$typeid}' AND topid<>'{$typeid}' "; - } - else { + } else { $arr['crossid'] = preg_replace('#[^0-9,]#', '', trim($arr['crossid'])); - if($arr['crossid']!='') $selquery = "SELECT id,topid FROM `#@__arctype` WHERE id IN('{$arr['crossid']}') AND id<>'{$typeid}' AND topid<>'{$typeid}' "; + if ($arr['crossid'] != '') { + $selquery = "SELECT id,topid FROM `#@__arctype` WHERE id IN('{$arr['crossid']}') AND id<>'{$typeid}' AND topid<>'{$typeid}' "; + } + } - if($selquery!='') - { + if ($selquery != '') { $dsql->SetQuery($selquery); $dsql->Execute(); - while($arr = $dsql->GetArray()) { - $CrossID .= ($CrossID=='' ? $arr['id'] : ','.$arr['id']); + while ($arr = $dsql->GetArray()) { + $CrossID .= ($CrossID == '' ? $arr['id'] : ',' . $arr['id']); } } } } - if($CrossID=='') $orwheres[] = ' typeid IN ('.GetSonIds($typeid).')'; - else $orwheres[] = ' typeid IN ('.GetSonIds($typeid).','.$CrossID.')'; + if ($CrossID == '') { + $orwheres[] = ' typeid IN (' . GetSonIds($typeid) . ')'; + } else { + $orwheres[] = ' typeid IN (' . GetSonIds($typeid) . ',' . $CrossID . ')'; + } + } } //频道ID - if(!empty($channelid)) $orwheres[] = " AND arc.channel = '$channelid' "; + if (!empty($channelid)) { + $orwheres[] = " AND arc.channel = '$channelid' "; + } //由于这个条件会导致缓存功能失去意义,因此取消 //if($arcid!=0) $orwheres[] = " arc.id<>'$arcid' "; } //文档排序的方式 $ordersql = ''; - if($orderby=='hot'||$orderby=='click') $ordersql = " ORDER BY arc.click $orderway"; - else if($orderby=='id') $ordersql = " ORDER BY arc.aid $orderway"; - else if($orderby=='near') $ordersql = " ORDER BY ABS(arc.id - ".$arcid.")"; - else if($orderby=='rand') $ordersql = " ORDER BY rand()"; - else $ordersql=" ORDER BY arc.aid $orderway"; + if ($orderby == 'hot' || $orderby == 'click') { + $ordersql = " ORDER BY arc.click $orderway"; + } else if ($orderby == 'id') { + $ordersql = " ORDER BY arc.aid $orderway"; + } else if ($orderby == 'near') { + $ordersql = " ORDER BY ABS(arc.id - " . $arcid . ")"; + } else if ($orderby == 'rand') { + $ordersql = " ORDER BY rand()"; + } else { + $ordersql = " ORDER BY arc.aid $orderway"; + } + //limit条件 $limit = trim(preg_replace('#limit#i', '', $limit)); - if($limit!='') $limitsql = " LIMIT $limit "; - else $limitsql = " LIMIT 0,$line "; + if ($limit != '') { + $limitsql = " LIMIT $limit "; + } else { + $limitsql = " LIMIT 0,$line "; + } $orwhere = ''; - if(isset($orwheres[0])) { - $orwhere = join(' AND ',$orwheres); + if (isset($orwheres[0])) { + $orwhere = join(' AND ', $orwheres); $orwhere = preg_replace("#^ AND#i", '', $orwhere); $orwhere = preg_replace("#AND[ ]{1,}AND#i", 'AND ', $orwhere); } - if($orwhere!='') $orwhere = " WHERE $orwhere "; + if ($orwhere != '') { + $orwhere = " WHERE $orwhere "; + } $query = "SELECT $arclistquery,tp.typedir,tp.typename,tp.isdefault,tp.defaultname,tp.namerule, tp.namerule2,tp.ispart,tp.moresite,tp.siteurl,tp.sitepath @@ -190,15 +219,18 @@ function lib_arclistsg(&$ctag,&$refObj) $orwhere AND arc.arcrank > -1 $ordersql $limitsql"; $md5hash = md5($query); - $needcache = TRUE; - if($idlist!='') $needcache = FALSE; - else{ + $needcache = true; + if ($idlist != '') { + $needcache = false; + } else { $idlist = GetArclistSgCache($md5hash); - if($idlist!='') $needcache = FALSE; + if ($idlist != '') { + $needcache = false; + } + } //指定了id或使用缓存中的id - if($idlist!='' && $_arclistEnv != 'index') - { + if ($idlist != '' && $_arclistEnv != 'index') { $query = "SELECT $arclistquery,tp.typedir,tp.typename,tp.isdefault,tp.defaultname,tp.namerule,tp.namerule2,tp.ispart, tp.moresite,tp.siteurl,tp.sitepath FROM `$maintable` arc LEFT JOIN `#@__arctype` tp ON arc.typeid=tp.id WHERE arc.aid IN($idlist) $ordersql $limitsql"; @@ -207,83 +239,85 @@ function lib_arclistsg(&$ctag,&$refObj) $dsql->Execute("al"); $artlist = ""; $dtp2 = new DedeTagParse(); - $dtp2->SetNameSpace("field","[","]"); + $dtp2->SetNameSpace("field", "[", "]"); $dtp2->LoadString($innertext); $GLOBALS['autoindex'] = 0; $ids = array(); - for($i=0;$i<$line;$i++) - { - for($j=0;$j<$col;$j++) - { - if($col>1) $artlist .= "
\r\n"; - if($row = $dsql->GetArray("al")) - { + for ($i = 0; $i < $line; $i++) { + for ($j = 0; $j < $col; $j++) { + if ($col > 1) { + $artlist .= "
\r\n"; + } + + if ($row = $dsql->GetArray("al")) { $ids[] = $row['aid']; - $row['filename'] = $row['arcurl'] = GetFileUrl($row['id'],$row['typeid'],$row['senddate'],$row['title'],1, - 0,$row['namerule'],$row['typedir'],0,'',$row['moresite'],$row['siteurl'],$row['sitepath']); + $row['filename'] = $row['arcurl'] = GetFileUrl($row['id'], $row['typeid'], $row['senddate'], $row['title'], 1, + 0, $row['namerule'], $row['typedir'], 0, '', $row['moresite'], $row['siteurl'], $row['sitepath']); - $row['typeurl'] = GetTypeUrl($row['typeid'],$row['typedir'],$row['isdefault'],$row['defaultname'],$row['ispart'], - $row['namerule2'],$row['moresite'],$row['siteurl'],$row['sitepath']); + $row['typeurl'] = GetTypeUrl($row['typeid'], $row['typedir'], $row['isdefault'], $row['defaultname'], $row['ispart'], + $row['namerule2'], $row['moresite'], $row['siteurl'], $row['sitepath']); - if($row['litpic'] == '-' || $row['litpic'] == '') - { - $row['litpic'] = $GLOBALS['cfg_cmspath'].'/resources/img/defaultpic.gif'; + if ($row['litpic'] == '-' || $row['litpic'] == '') { + $row['litpic'] = $GLOBALS['cfg_cmspath'] . '/resources/img/defaultpic.gif'; } - if(!preg_match("#^http:\/\/#i", $row['litpic']) && $GLOBALS['cfg_multi_site'] == 'Y') - { - $row['litpic'] = $GLOBALS['cfg_mainsite'].$row['litpic']; + if (!preg_match("#^http:\/\/#i", $row['litpic']) && $GLOBALS['cfg_multi_site'] == 'Y') { + $row['litpic'] = $GLOBALS['cfg_mainsite'] . $row['litpic']; } $row['picname'] = $row['litpic']; - - $row['image'] = "".preg_replace("#[<]#", "", $row['title'])."' />"; - $row['imglink'] = "".$row['image'].""; + $row['image'] = "" . preg_replace("#[<]#", "", $row['title']) . "' />"; + + $row['imglink'] = "" . $row['image'] . ""; $row['stime'] = GetDateMK($row['pubdate']); - $row['typelink'] = "".$row['typename'].""; + $row['typelink'] = "" . $row['typename'] . ""; $row['fulltitle'] = $row['title']; - $row['title'] = cn_substr($row['title'],$titlelen); - $row['textlink'] = "".$row['title'].""; + $row['title'] = cn_substr($row['title'], $titlelen); + $row['textlink'] = "" . $row['title'] . ""; $row['plusurl'] = $row['phpurl'] = $GLOBALS['cfg_phpurl']; $row['memberurl'] = $GLOBALS['cfg_memberurl']; $row['templeturl'] = $GLOBALS['cfg_templeturl']; - if(is_array($dtp2->CTags)) - { - foreach($dtp2->CTags as $k=>$ctag) - { - if($ctag->GetName()=='array') - { + if (is_array($dtp2->CTags)) { + foreach ($dtp2->CTags as $k => $ctag) { + if ($ctag->GetName() == 'array') { //传递整个数组,在runphp模式中有特殊作用 - $dtp2->Assign($k,$row); - } - else - { - if(isset($row[$ctag->GetName()])) $dtp2->Assign($k,$row[$ctag->GetName()]); - else $dtp2->Assign($k,''); + $dtp2->Assign($k, $row); + } else { + if (isset($row[$ctag->GetName()])) { + $dtp2->Assign($k, $row[$ctag->GetName()]); + } else { + $dtp2->Assign($k, ''); + } + } } $GLOBALS['autoindex']++; } - $artlist .= $dtp2->GetResult()."\r\n"; - }//if hasRow - else{ + $artlist .= $dtp2->GetResult() . "\r\n"; + } //if hasRow + else { $artlist .= ''; } - if($col>1) $artlist .= "
\r\n"; - }//Loop Col - if($col>1) $i += $col - 1; - }//loop line + if ($col > 1) { + $artlist .= "
\r\n"; + } + + } //Loop Col + if ($col > 1) { + $i += $col - 1; + } + + } //loop line $dsql->FreeResult("al"); //保存ID缓存 - $idsstr = join(',',$ids); - if($idsstr!='' && $needcache && $cfg_index_cache>0) - { + $idsstr = join(',', $ids); + if ($idsstr != '' && $needcache && $cfg_index_cache > 0) { $mintime = time() - ($cfg_index_cache * 3600); - $inquery = "INSERT INTO `#@__arccache`(`md5hash`,`uptime`,`cachedata`) VALUES ('".$md5hash."', '".time()."', '$idsstr'); "; - $dsql->ExecuteNoneQuery("DELETE FROM `#@__arccache` WHERE md5hash='".$md5hash."' or uptime < $mintime "); + $inquery = "INSERT INTO `#@__arccache`(`md5hash`,`uptime`,`cachedata`) VALUES ('" . $md5hash . "', '" . time() . "', '$idsstr'); "; + $dsql->ExecuteNoneQuery("DELETE FROM `#@__arccache` WHERE md5hash='" . $md5hash . "' or uptime < $mintime "); $dsql->ExecuteNoneQuery($inquery); } return $artlist; @@ -292,26 +326,45 @@ function lib_arclistsg(&$ctag,&$refObj) //查询缓存 function GetArclistSgCache($md5hash) { - global $dsql,$envs,$cfg_makesign_cache,$cfg_index_cache; + global $dsql, $envs, $cfg_makesign_cache, $cfg_index_cache; //没启用缓存 - if($cfg_index_cache<=0) return ''; + if ($cfg_index_cache <= 0) { + return ''; + } + //少量更新禁用缓存 - if(isset($envs['makesign']) && $cfg_makesign_cache=='N') return ''; + if (isset($envs['makesign']) && $cfg_makesign_cache == 'N') { + return ''; + } + //正常情况 $mintime = time() - ($cfg_index_cache * 3600); $arr = $dsql->GetOne("SELECT cachedata,uptime FROM `#@__arccache` WHERE md5hash = '$md5hash' AND uptime > $mintime "); //没数据 - if(!is_array($arr)) return ''; + if (!is_array($arr)) { + return ''; + } + //返回缓存id数据 - else return $arr['cachedata']; + else { + return $arr['cachedata']; + } + } -function lib_GetAutoChannelID2($sortid,$topid) +function lib_GetAutoChannelID2($sortid, $topid) { global $dsql; - if(empty($sortid)) $sortid = 1; + if (empty($sortid)) { + $sortid = 1; + } + $getstart = $sortid - 1; $row = $dsql->GetOne("SELECT id,typename From #@__arctype WHERE reid='{$topid}' AND ispart<2 AND ishidden<>'1' ORDER BY sortrank asc limit $getstart,1"); - if(!is_array($row)) return 0; - else return $row['id']; -} \ No newline at end of file + if (!is_array($row)) { + return 0; + } else { + return $row['id']; + } + +} diff --git a/include/taglib/arcpagelist.lib.php b/include/taglib/arcpagelist.lib.php index ac5eaf21..f436f217 100755 --- a/include/taglib/arcpagelist.lib.php +++ b/include/taglib/arcpagelist.lib.php @@ -1,6 +1,5 @@ -CAttribute->Items,$attlist); + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - + $row = $dsql->GetOne("SELECT * FROM #@__arcmulti WHERE tagid='$tagid'"); - if(is_array($row)) - { - $ids = explode(',', $row['arcids']); - - $totalnum = count($ids); - $pagestr = '
'; - if($row['pagesize'] < $totalnum) - { - $pagestr .= multipage($totalnum, 1, $row['pagesize'], $tagid); - } else { - $pagestr .= '共1页'; - } - $pagestr .= '
'; - return $pagestr; + if (is_array($row)) { + $ids = explode(',', $row['arcids']); + + $totalnum = count($ids); + $pagestr = '
'; + if ($row['pagesize'] < $totalnum) { + $pagestr .= multipage($totalnum, 1, $row['pagesize'], $tagid); + } else { + $pagestr .= '共1页'; + } + $pagestr .= '
'; + return $pagestr; } else { - $pagestr = '
'; - $pagestr .= '没有检索到对应分页'; - $pagestr .= '
'; + $pagestr = '
'; + $pagestr .= '没有检索到对应分页'; + $pagestr .= '
'; return $pagestr; } } @@ -49,33 +46,42 @@ function lib_arcpagelist(&$ctag, &$refObj) * @param string $tagid 标签ID * @return string */ -function multipage($allItemTotal, $currPageNum, $pageSize, $tagid='') +function multipage($allItemTotal, $currPageNum, $pageSize, $tagid = '') { - if ($allItemTotal == 0) return ""; + if ($allItemTotal == 0) { + return ""; + } //计算总页数 - $pagesNum = ceil($allItemTotal/$pageSize); + $pagesNum = ceil($allItemTotal / $pageSize); //第一页显示 - $firstPage = ($currPageNum <= 1) ? $currPageNum ."<<" : "1<<"; + $firstPage = ($currPageNum <= 1) ? $currPageNum . "<<" : "1<<"; //最后一页显示 - $lastPage = ($currPageNum >= $pagesNum)? ">>". $currPageNum : ">>". $pagesNum .""; + $lastPage = ($currPageNum >= $pagesNum) ? ">>" . $currPageNum : ">>" . $pagesNum . ""; //上一页显示 - $prePage = ($currPageNum <= 1) ? "上页" : "[上一页]"; + $prePage = ($currPageNum <= 1) ? "上页" : "[上一页]"; //下一页显示 - $nextPage = ($currPageNum >= $pagesNum) ? "下页" : "[下一页]"; + $nextPage = ($currPageNum >= $pagesNum) ? "下页" : "[下一页]"; //按页显示 $listNums = ""; - for ($i=($currPageNum-4); $i<($currPageNum+9); $i++) { - if ($i < 1 || $i > $pagesNum) continue; - if ($i == $currPageNum) $listNums.= "".$i.""; - else $listNums.= " ". $i ." "; + for ($i = ($currPageNum - 4); $i < ($currPageNum + 9); $i++) { + if ($i < 1 || $i > $pagesNum) { + continue; + } + + if ($i == $currPageNum) { + $listNums .= "" . $i . ""; + } else { + $listNums .= " " . $i . " "; + } + } $returnUrl = $listNums; return $returnUrl; -} \ No newline at end of file +} diff --git a/include/taglib/ask.lib.php b/include/taglib/ask.lib.php index 787d0718..4c772344 100755 --- a/include/taglib/ask.lib.php +++ b/include/taglib/ask.lib.php @@ -1,4 +1,4 @@ -CAttribute->Items,$attlist); + $attlist = "row|6,qtype|new,tid|0,titlelen|24"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - - if( !$dsql->IsTable("{$cfg_dbprefix}ask") ) return '没安装问答模块'; - + + if (!$dsql->IsTable("{$cfg_dbprefix}ask")) { + return '没安装问答模块'; + } + //启用二级域名 - if($cfg_ask_isdomain == 'Y') - { - $weburl = $cfg_ask_domain.'/'; - }else{ - $weburl = $cfg_ask_directory.'/'; + if ($cfg_ask_isdomain == 'Y') { + $weburl = $cfg_ask_domain . '/'; + } else { + $weburl = $cfg_ask_directory . '/'; } - + $innertext = $ctag->GetInnerText(); - if(trim($innertext)=='') $innertext = GetSysTemplets("asks.htm"); - + if (trim($innertext) == '') { + $innertext = GetSysTemplets("asks.htm"); + } + $qtypeQuery = ''; - if($tid > 0) $tid = " (tid=$tid Or tid2='$tid') AND "; - else $tid = ''; + if ($tid > 0) { + $tid = " (tid=$tid Or tid2='$tid') AND "; + } else { + $tid = ''; + } + //推荐问题 - if($qtype=='commend') $qtypeQuery = " $tid digest=1 ORDER BY dateline DESC "; + if ($qtype == 'commend') { + $qtypeQuery = " $tid digest=1 ORDER BY dateline DESC "; + } + //新解决问题 - else if($qtype=='ok') $qtypeQuery = " $tid status=1 ORDER BY solvetime DESC "; + else if ($qtype == 'ok') { + $qtypeQuery = " $tid status=1 ORDER BY solvetime DESC "; + } + //高分问题 - else if($qtype=='high') $qtypeQuery = " $tid status=0 ORDER BY reward DESC "; + else if ($qtype == 'high') { + $qtypeQuery = " $tid status=0 ORDER BY reward DESC "; + } + //新问题 - else $qtypeQuery = " $tid status=0 ORDER BY disorder DESC, dateline DESC "; + else { + $qtypeQuery = " $tid status=0 ORDER BY disorder DESC, dateline DESC "; + } $ctp = new DedeTagParse(); $ctp->SetNameSpace('field', '[', ']'); $solvingask = ''; $query = "SELECT id, tid, tidname, tid2, tid2name, title,dateline FROM `#@__ask` WHERE $qtypeQuery limit 0, $row"; - $dsql->Execute('me',$query); - - while($rs = $dsql->GetArray('me')) - { + $dsql->Execute('me', $query); + + while ($rs = $dsql->GetArray('me')) { $rs['title'] = cn_substr($rs['title'], $titlelen); $ctp->LoadSource($innertext); - if($rs['tid2name'] != '') - { + if ($rs['tid2name'] != '') { $rs['tid'] = $rs['tid2']; $rs['tidname'] = $rs['tid2name']; } - $rs['url'] = $weburl."?ct=question&askaid=".$rs['id']; - foreach($ctp->CTags as $tagid=>$ctag) { - if(!empty($rs[strtolower($ctag->GetName())])) { - $ctp->Assign($tagid,$rs[$ctag->GetName()]); + $rs['url'] = $weburl . "?ct=question&askaid=" . $rs['id']; + foreach ($ctp->CTags as $tagid => $ctag) { + if (!empty($rs[strtolower($ctag->GetName())])) { + $ctp->Assign($tagid, $rs[$ctag->GetName()]); } } $solvingask .= $ctp->GetResult(); } return $solvingask; -} \ No newline at end of file +} diff --git a/include/taglib/asktype.lib.php b/include/taglib/asktype.lib.php index 93cd0c26..63914dc2 100755 --- a/include/taglib/asktype.lib.php +++ b/include/taglib/asktype.lib.php @@ -1,4 +1,4 @@ -CAttribute->Items,$attlist); + $attlist = "tid|0,reid|0,name|24"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - - if( !$dsql->IsTable("{$cfg_dbprefix}ask") ) return '没安装问答模块'; - + + if (!$dsql->IsTable("{$cfg_dbprefix}ask")) { + return '没安装问答模块'; + } + //启用二级域名 - if($cfg_ask_isdomain == 'Y') - { - $weburl = $cfg_ask_domain.'/'; - }else{ - $weburl = $cfg_ask_directory.'/'; + if ($cfg_ask_isdomain == 'Y') { + $weburl = $cfg_ask_domain . '/'; + } else { + $weburl = $cfg_ask_directory . '/'; } - + $innertext = $ctag->GetInnerText(); - if(trim($innertext)=='') $innertext = GetSysTemplets("asks.htm"); - - if($tid > 0) $qtypeQuery = "WHERE reid=$tid "; - else $qtypeQuery = ''; - if($reid > 0) $qtypeQuery = "WHERE reid > 0 "; + if (trim($innertext) == '') { + $innertext = GetSysTemplets("asks.htm"); + } + + if ($tid > 0) { + $qtypeQuery = "WHERE reid=$tid "; + } else { + $qtypeQuery = ''; + } + + if ($reid > 0) { + $qtypeQuery = "WHERE reid > 0 "; + } $ctp = new DedeTagParse(); $ctp->SetNameSpace('field', '[', ']'); $solvingask = ''; $query = "SELECT id,name,reid FROM `#@__asktype` $qtypeQuery"; - $dsql->Execute('me',$query); - while($rs = $dsql->GetArray('me')) - { + $dsql->Execute('me', $query); + while ($rs = $dsql->GetArray('me')) { $ctp->LoadSource($innertext); - if($rs['reid'] != '') - $rs['typeurl'] = $weburl."?ct=browser&tid2=".$rs['id']; - else - $rs['typeurl'] = $weburl."?ct=browser&tid=".$rs['id']; - foreach($ctp->CTags as $tagid=>$ctag) { - if(!empty($rs[strtolower($ctag->GetName())])) { - $ctp->Assign($tagid,$rs[$ctag->GetName()]); + if ($rs['reid'] != '') { + $rs['typeurl'] = $weburl . "?ct=browser&tid2=" . $rs['id']; + } else { + $rs['typeurl'] = $weburl . "?ct=browser&tid=" . $rs['id']; + } + + foreach ($ctp->CTags as $tagid => $ctag) { + if (!empty($rs[strtolower($ctag->GetName())])) { + $ctp->Assign($tagid, $rs[$ctag->GetName()]); } } $solvingask .= $ctp->GetResult(); } return $solvingask; -} \ No newline at end of file +} diff --git a/include/taglib/autochannel.lib.php b/include/taglib/autochannel.lib.php index 72a51a16..ead6a9e8 100755 --- a/include/taglib/autochannel.lib.php +++ b/include/taglib/autochannel.lib.php @@ -1,4 +1,4 @@ ->dede>> + +/*>>dede>> 指定栏目 全局标记 V55,V56,V57 @@ -18,61 +18,69 @@ {dede:autochannel partsort='' typeid=’’}{/dede:autochannel} - partsort:栏目所在的排序位置 - typeid:获取单个栏目的顶级栏目 - +partsort:栏目所在的排序位置 +typeid:获取单个栏目的顶级栏目 + >>dede>>*/ - -function lib_autochannel(&$ctag,&$refObj) + +function lib_autochannel(&$ctag, &$refObj) { global $dsql; - $attlist='partsort|0,typeid=-1'; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = 'partsort|0,typeid=-1'; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $innertext = trim($ctag->GetInnerText()); $topid = $typeid; $sortid = $partsort; - if($topid=='-1' || $topid=='') - { - $topid = ( isset($refObj->TypeLink->TypeInfos['id']) ? $refObj->TypeLink->TypeInfos['id'] : 0); + if ($topid == '-1' || $topid == '') { + $topid = (isset($refObj->TypeLink->TypeInfos['id']) ? $refObj->TypeLink->TypeInfos['id'] : 0); + } + + if (empty($sortid)) { + $sortid = 1; } - - if(empty($sortid)) $sortid = 1; + $getstart = $sortid - 1; - $row = $dsql->GetOne("SELECT id,typename FROM `#@__arctype` WHERE reid='{$topid}' AND + $row = $dsql->GetOne("SELECT id,typename FROM `#@__arctype` WHERE reid='{$topid}' AND ispart<2 AND ishidden<>'1' ORDER BY sortrank asc limit $getstart,1"); - - if(!is_array($row) ) return ''; - else $typeid = $row['id']; - - if(trim($innertext)=='') $innertext = GetSysTemplets('part_autochannel.htm'); - - $row = $dsql->GetOne("SELECT id,typedir,isdefault,defaultname,ispart,namerule2,typename,moresite,siteurl,sitepath + + if (!is_array($row)) { + return ''; + } else { + $typeid = $row['id']; + } + + if (trim($innertext) == '') { + $innertext = GetSysTemplets('part_autochannel.htm'); + } + + $row = $dsql->GetOne("SELECT id,typedir,isdefault,defaultname,ispart,namerule2,typename,moresite,siteurl,sitepath FROM `#@__arctype` WHERE id='$typeid' "); - if(!is_array($row)) return ''; + if (!is_array($row)) { + return ''; + } $dtp = new DedeTagParse(); - $dtp->SetNameSpace('field','[',']'); + $dtp->SetNameSpace('field', '[', ']'); $dtp->LoadSource($innertext); - if(!is_array($dtp->CTags)) - { + if (!is_array($dtp->CTags)) { unset($dtp); return ''; - } - else - { - $row['typelink'] = GetTypeUrl($row['id'],MfTypedir($row['typedir']),$row['isdefault'], - $row['defaultname'],$row['ispart'],$row['namerule2'],$row['siteurl'],$row['sitepath']); - foreach($dtp->CTags as $tagid=>$ctag) - { - if(isset($row[$ctag->GetName()])) $dtp->Assign($tagid,$row[$ctag->GetName()]); + } else { + $row['typelink'] = GetTypeUrl($row['id'], MfTypedir($row['typedir']), $row['isdefault'], + $row['defaultname'], $row['ispart'], $row['namerule2'], $row['siteurl'], $row['sitepath']); + foreach ($dtp->CTags as $tagid => $ctag) { + if (isset($row[$ctag->GetName()])) { + $dtp->Assign($tagid, $row[$ctag->GetName()]); + } + } $revalue = $dtp->GetResult(); unset($dtp); return $revalue; } -} \ No newline at end of file +} diff --git a/include/taglib/bookcontentlist.lib.php b/include/taglib/bookcontentlist.lib.php index 4eb2ccf9..30a36a68 100755 --- a/include/taglib/bookcontentlist.lib.php +++ b/include/taglib/bookcontentlist.lib.php @@ -1,4 +1,4 @@ ->dede>> 连载内容 全局标记 @@ -24,29 +24,31 @@ [field:lastpost function="GetDateMk(@me)"/] -{/dede:bookcontentlist} +{/dede:bookcontentlist} - row:调用记录条数 - booktype:图书类型,0 图书、1 漫画,默认全部 - orderby:排序类型,当按排序类型为 commend 表示推荐图书 - author:作者 - keyword:关键字 - +row:调用记录条数 +booktype:图书类型,0 图书、1 漫画,默认全部 +orderby:排序类型,当按排序类型为 commend 表示推荐图书 +author:作者 +keyword:关键字 + >>dede>>*/ - -require_once(DEDEINC.'/taglib/booklist.lib.php'); + +require_once DEDEINC . '/taglib/booklist.lib.php'; function lib_bookcontentlist(&$ctag, &$refObj) { global $dsql, $envs, $cfg_dbprefix, $cfg_cmsurl; - $attlist="row|12,booktype|-1,titlelen|30,orderby|lastpost,author|,keyword|"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "row|12,booktype|-1,titlelen|30,orderby|lastpost,author|,keyword|"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - if( !$dsql->IsTable("{$cfg_dbprefix}story_books") ) return '没安装连载模块'; - + if (!$dsql->IsTable("{$cfg_dbprefix}story_books")) { + return '没安装连载模块'; + } + return lib_booklist($ctag, $refObj, 1); - -} \ No newline at end of file + +} diff --git a/include/taglib/booklist.lib.php b/include/taglib/booklist.lib.php index 4d4cd4ba..76d2d222 100755 --- a/include/taglib/booklist.lib.php +++ b/include/taglib/booklist.lib.php @@ -1,4 +1,4 @@ ->dede>> 连载图书 全局标记 @@ -30,65 +30,68 @@ {/dede:booklist} - row:调用记录条数 - booktype:图书类型,0 图书、1 漫画,默认全部 - orderby:排序类型,当按排序类型为 commend 表示推荐图书 - author:作者 - keyword:关键字 - +row:调用记录条数 +booktype:图书类型,0 图书、1 漫画,默认全部 +orderby:排序类型,当按排序类型为 commend 表示推荐图书 +author:作者 +keyword:关键字 + >>dede>>*/ -function lib_booklist(&$ctag, &$refObj, $getcontent=0) +function lib_booklist(&$ctag, &$refObj, $getcontent = 0) { global $dsql, $envs, $cfg_dbprefix, $cfg_cmsurl; - + //属性处理 - $attlist="row|12,booktype|-1,titlelen|30,orderby|lastpost,author|,keyword|"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "row|12,booktype|-1,titlelen|30,orderby|lastpost,author|,keyword|"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - if( !$dsql->IsTable("{$cfg_dbprefix}story_books") ) return '没安装连载模块'; + if (!$dsql->IsTable("{$cfg_dbprefix}story_books")) { + return '没安装连载模块'; + } + $addquery = ''; - - if(empty($innertext)) - { - if($getcontent==0) $innertext = GetSysTemplets('booklist.htm'); - else $innertext = GetSysTemplets('bookcontentlist.htm'); + + if (empty($innertext)) { + if ($getcontent == 0) { + $innertext = GetSysTemplets('booklist.htm'); + } else { + $innertext = GetSysTemplets('bookcontentlist.htm'); + } + } - + //图书类型 - if($booktype!=-1) { + if ($booktype != -1) { $addquery .= " AND b.booktype='{$booktype}' "; } - + //推荐 - if($orderby=='commend') - { + if ($orderby == 'commend') { $addquery .= " AND b.iscommend=1 "; $orderby = 'lastpost'; } //作者条件 - if(!empty($author)) - { + if (!empty($author)) { $addquery .= " AND b.author LIKE '$author' "; } - + //关键字条件 - if(!empty($keyword)) - { + if (!empty($keyword)) { $keywords = explode(',', $keyword); $keywords = array_unique($keywords); - if(count($keywords) > 0) { + if (count($keywords) > 0) { $addquery .= " AND ("; } - foreach($keywords as $v) { + foreach ($keywords as $v) { $addquery .= " CONCAT(b.author,b.bookname,b.keywords) LIKE '%$v%' OR"; } $addquery = preg_replace("# OR$#", "", $addquery); $addquery .= ")"; } - + $clist = ''; $query = "SELECT b.id,b.catid,b.ischeck,b.booktype,b.iscommend,b.click,b.bookname,b.lastpost, b.author,b.mid,b.litpic,b.pubdate,b.weekcc,b.monthcc,b.description,c.classname,c.classname as typename,c.booktype as catalogtype @@ -100,8 +103,7 @@ function lib_booklist(&$ctag, &$refObj, $getcontent=0) $ndtp = new DedeTagParse(); $ndtp->SetNameSpace('field', '[', ']'); $GLOBALS['autoindex'] = 0; - while($row = $dsql->GetArray()) - { + while ($row = $dsql->GetArray()) { $GLOBALS['autoindex']++; $row['title'] = $row['bookname']; $ndtp->LoadString($innertext); @@ -109,46 +111,53 @@ function lib_booklist(&$ctag, &$refObj, $getcontent=0) //获得图书最新的一个更新章节 $row['contenttitle'] = ''; $row['contentid'] = ''; - if($getcontent==1) { + if ($getcontent == 1) { $nrow = $dsql->GetOne("SELECT id,title,chapterid FROM `#@__story_content` WHERE bookid='{$row['id']}' order by id desc "); $row['contenttitle'] = $nrow['title']; $row['contentid'] = $nrow['id']; } - if($row['booktype']==1) { - $row['contenturl'] = $cfg_cmspath.'/book/show-photo.php?id='.$row['contentid']; - } - else { - $row['contenturl'] = $cfg_cmspath.'/book/story.php?id='.$row['contentid']; + if ($row['booktype'] == 1) { + $row['contenturl'] = $cfg_cmspath . '/book/show-photo.php?id=' . $row['contentid']; + } else { + $row['contenturl'] = $cfg_cmspath . '/book/story.php?id=' . $row['contentid']; } //动态网址 - $row['dmbookurl'] = $cfg_cmspath.'/book/book.php?id='.$row['id']; + $row['dmbookurl'] = $cfg_cmspath . '/book/book.php?id=' . $row['id']; //静态网址 - $row['bookurl'] = $row['url'] = GetBookUrl($row['id'],$row['bookname']); - $row['catalogurl'] = $cfg_cmspath.'/book/list.php?id='.$row['catid']; + $row['bookurl'] = $row['url'] = GetBookUrl($row['id'], $row['bookname']); + $row['catalogurl'] = $cfg_cmspath . '/book/list.php?id=' . $row['catid']; $row['cataloglink'] = "{$row['classname']}"; $row['booklink'] = "{$row['bookname']}"; $row['contentlink'] = "{$row['contenttitle']}"; $row['imglink'] = ""; - - if($row['ischeck']==2) $row['ischeck']='已完成连载'; - else $row['ischeck']='连载中...'; - if($row['booktype']==0) $row['booktypename']='小说'; - else $row['booktypename']='漫画'; + if ($row['ischeck'] == 2) { + $row['ischeck'] = '已完成连载'; + } else { + $row['ischeck'] = '连载中...'; + } + + if ($row['booktype'] == 0) { + $row['booktypename'] = '小说'; + } else { + $row['booktypename'] = '漫画'; + } - if(is_array($ndtp->CTags)) - { - foreach($ndtp->CTags as $tagid=>$ctag) - { + if (is_array($ndtp->CTags)) { + foreach ($ndtp->CTags as $tagid => $ctag) { $tagname = $ctag->GetTagName(); - if(isset($row[$tagname])) $ndtp->Assign($tagid,$row[$tagname]); - else $ndtp->Assign($tagid,''); + if (isset($row[$tagname])) { + $ndtp->Assign($tagid, $row[$tagname]); + } else { + $ndtp->Assign($tagid, ''); + } + } } $clist .= $ndtp->GetResult(); } - + return $clist; -} \ No newline at end of file +} diff --git a/include/taglib/cattree.lib.php b/include/taglib/cattree.lib.php index af60ccb2..ae5d0c87 100755 --- a/include/taglib/cattree.lib.php +++ b/include/taglib/cattree.lib.php @@ -1,6 +1,6 @@ ->dede>> + +/*>>dede>> 树形类目标签 全局标记 V55,V56,V57 @@ -18,41 +18,40 @@ {dede:cattree typeid='' catid='' showall=''/} - typeid:顶级树id - catid:上级栏目id - showall:在空或不存在时,强制用产品模型id;如果是 yes 刚显示整个语言区栏目树;为其它数字则是这个数字的模型的id - +typeid:顶级树id +catid:上级栏目id +showall:在空或不存在时,强制用产品模型id;如果是 yes 刚显示整个语言区栏目树;为其它数字则是这个数字的模型的id + >>dede>>*/ - + function lib_cattree(&$ctag, &$refObj) { global $dsql; //属性处理 //属性 showall 在空或不存在时,强制用产品模型id;如果是 yes 刚显示整个语言区栏目树;为其它数字则是这个数字的模型的id //typeid 指定顶级树 id ,指定后,前一个属性将无效 - $attlist="showall|,catid|0"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "showall|,catid|0"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $revalue = ''; - if(empty($typeid)) - { - if( isset($refObj->TypeLink->TypeInfos['id']) ) { + if (empty($typeid)) { + if (isset($refObj->TypeLink->TypeInfos['id'])) { $typeid = $refObj->TypeLink->TypeInfos['id']; $reid = $refObj->TypeLink->TypeInfos['reid']; $topid = $refObj->TypeLink->TypeInfos['topid']; $channeltype = $refObj->TypeLink->TypeInfos['channeltype']; $ispart = $refObj->TypeLink->TypeInfos['ispart']; - if($reid==0) $topid = $typeid; + if ($reid == 0) { + $topid = $typeid; + } + } else { - $typeid = $reid = $topid = $channeltype = $ispart = 0; + $typeid = $reid = $topid = $channeltype = $ispart = 0; } - } - else - { + } else { $row = $dsql->GetOne("SELECT reid,topid,channeltype,ispart FROM `#@__arctype` WHERE id='$typeid' "); - if(!is_array($row)) - { + if (!is_array($row)) { $typeid = $reid = $topid = $channeltype = $ispart = 0; } else { $reid = $row['reid']; @@ -61,35 +60,31 @@ function lib_cattree(&$ctag, &$refObj) $ispart = $row['ispart']; } } - if( !empty($catid) ) - { + if (!empty($catid)) { $topQuery = "SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath FROM `#@__arctype` WHERE reid='$catid' And ishidden<>1 "; - } - else - { - if($showall == "yes" ) - { + } else { + if ($showall == "yes") { $topQuery = "SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath FROM `#@__arctype` WHERE reid='$topid' "; - } - else - { - if($showall=='') - { - if( $ispart < 2 && !empty($channeltype) ) $showall = $channeltype; - else $showall = 6; - } - $topQuery = "SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath FROM `#@__arctype` WHERE reid='{$topid}' And channeltype='{$showall}' And ispart<2 And ishidden<>1 "; + } else { + if ($showall == '') { + if ($ispart < 2 && !empty($channeltype)) { + $showall = $channeltype; + } else { + $showall = 6; + } + + } + $topQuery = "SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath FROM `#@__arctype` WHERE reid='{$topid}' And channeltype='{$showall}' And ispart<2 And ishidden<>1 "; } } - $dsql->Execute('t', $topQuery); - while($row = $dsql->GetArray('t')) - { - $row['typelink'] = GetOneTypeUrlA($row); - $revalue .= "
\n"; - $revalue .= "
{$row['typename']}
\n"; - cattreeListSon($row['id'], $revalue); - $revalue .= "
\n"; - } + $dsql->Execute('t', $topQuery); + while ($row = $dsql->GetArray('t')) { + $row['typelink'] = GetOneTypeUrlA($row); + $revalue .= "
\n"; + $revalue .= "
{$row['typename']}
\n"; + cattreeListSon($row['id'], $revalue); + $revalue .= "
\n"; + } return $revalue; } @@ -99,13 +94,15 @@ function cattreeListSon($id, &$revalue) $query = "SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath FROM `#@__arctype` WHERE reid='{$id}' And ishidden<>1 "; $dsql->Execute($id, $query); $thisv = ''; - while($row = $dsql->GetArray($id)) - { - $row['typelink'] = GetOneTypeUrlA($row); - $thisv .= "
\n"; - $thisv .= "
{$row['typename']}
\n"; - cattreeListSon($row['id'], $thisv); - $thisv .= "
\n"; - } - if($thisv!='') $revalue .= "
\n$thisv
\n"; -} \ No newline at end of file + while ($row = $dsql->GetArray($id)) { + $row['typelink'] = GetOneTypeUrlA($row); + $thisv .= "
\n"; + $thisv .= "
{$row['typename']}
\n"; + cattreeListSon($row['id'], $thisv); + $thisv .= "
\n"; + } + if ($thisv != '') { + $revalue .= "
\n$thisv
\n"; + } + +} diff --git a/include/taglib/channel.lib.php b/include/taglib/channel.lib.php index 3a524778..c7011672 100755 --- a/include/taglib/channel.lib.php +++ b/include/taglib/channel.lib.php @@ -8,165 +8,180 @@ * @license http://help.dedecms.com/usersguide/license.html * @link http://www.dedecms.com */ - + /*>>dede>> 频道标签 全局标记 V55,V56,V57 用于获取栏目列表 -{dede:channel type='top' row='8' currentstyle="
  • ~typename~
  • "} -
  • [field:typename/]
  • +{dede:channel type='top' row='8' currentstyle="
  • ~typename~
  • "} +
  • [field:typename/]
  • {/dede:channel}
    - typeid:栏目ID - reid:上级栏目ID - row:调用栏目数 - col:分多少列显示(默认为单列) - type:son表示下级栏目,self表示同级栏目,top顶级栏目 - currentstyle:应用样式 - +typeid:栏目ID +reid:上级栏目ID +row:调用栏目数 +col:分多少列显示(默认为单列) +type:son表示下级栏目,self表示同级栏目,top顶级栏目 +currentstyle:应用样式 + >>dede>>*/ - -function lib_channel(&$ctag,&$refObj) + +function lib_channel(&$ctag, &$refObj) { global $dsql; $attlist = "typeid|0,reid|0,row|100,col|1,type|son,currentstyle|,cacheid|"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $innertext = $ctag->GetInnerText(); $line = empty($row) ? 100 : $row; - + $likeType = ''; //读取固定的缓存块 $cacheid = trim($cacheid); - if($cacheid !='') { + if ($cacheid != '') { $likeType = GetCacheBlock($cacheid); - if($likeType != '') return $likeType; + if ($likeType != '') { + return $likeType; + } + } $reid = 0; $topid = 0; //如果属性里没指定栏目id,从引用类里获取栏目信息 - if(empty($typeid)) - { - if( isset($refObj->TypeLink->TypeInfos['id']) ) - { + if (empty($typeid)) { + if (isset($refObj->TypeLink->TypeInfos['id'])) { $typeid = $refObj->TypeLink->TypeInfos['id']; $reid = $refObj->TypeLink->TypeInfos['reid']; $topid = $refObj->TypeLink->TypeInfos['topid']; + } else { + $typeid = 0; } - else { - $typeid = 0; - } } //如果指定了栏目id,从数据库获取栏目信息 - else - { + else { $row2 = $dsql->GetOne("SELECT * FROM `#@__arctype` WHERE id='$typeid' "); $typeid = $row2['id']; $reid = $row2['reid']; $topid = $row2['topid']; $issetInfos = true; } - - if($type=='' || $type=='sun') $type='son'; - if($innertext=='') $innertext = GetSysTemplets("channel_list.htm"); - if($type=='top') - { + if ($type == '' || $type == 'sun') { + $type = 'son'; + } + + if ($innertext == '') { + $innertext = GetSysTemplets("channel_list.htm"); + } + + if ($type == 'top') { $sql = "SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath From `#@__arctype` WHERE reid=0 And ishidden<>1 order by sortrank asc limit 0, $line "; - } - else if($type=='son') - { - if($typeid==0) return ''; + } else if ($type == 'son') { + if ($typeid == 0) { + return ''; + } + $sql = "SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath From `#@__arctype` WHERE reid='$typeid' And ishidden<>1 order by sortrank asc limit 0, $line "; - } - else if($type=='self') - { - if($reid==0) return ''; + } else if ($type == 'self') { + if ($reid == 0) { + return ''; + } + $sql = "SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath FROM `#@__arctype` WHERE reid='$reid' And ishidden<>1 order by sortrank asc limit 0, $line "; } //And id<>'$typeid' $needRel = false; $dtp2 = new DedeTagParse(); - $dtp2->SetNameSpace('field','[',']'); + $dtp2->SetNameSpace('field', '[', ']'); $dtp2->LoadSource($innertext); //检查是否有子栏目,并返回rel提示(用于二级菜单) - if(preg_match('#:rel#', $innertext)) $needRel = true; - - if(empty($sql)) return ''; + if (preg_match('#:rel#', $innertext)) { + $needRel = true; + } + + if (empty($sql)) { + return ''; + } + $dsql->SetQuery($sql); $dsql->Execute(); - + $totalRow = $dsql->GetTotalRow(); //如果用子栏目模式,当没有子栏目时显示同级栏目 - if($type=='son' && $reid!=0 && $totalRow==0) - { + if ($type == 'son' && $reid != 0 && $totalRow == 0) { $sql = "SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath FROM `#@__arctype` WHERE reid='$reid' And ishidden<>1 order by sortrank asc limit 0, $line "; $dsql->SetQuery($sql); - $dsql->Execute(); + $dsql->Execute(); } $GLOBALS['autoindex'] = 0; - for($i=0;$i < $line;$i++) - { - if($col>1) $likeType .= "
    \r\n"; - for($j=0; $j<$col; $j++) - { - if($col>1) $likeType .= "
    \r\n"; - if($row=$dsql->GetArray()) - { + for ($i = 0; $i < $line; $i++) { + if ($col > 1) { + $likeType .= "
    \r\n"; + } + + for ($j = 0; $j < $col; $j++) { + if ($col > 1) { + $likeType .= "
    \r\n"; + } + + if ($row = $dsql->GetArray()) { $row['sonids'] = $row['rel'] = ''; - if($needRel) - { + if ($needRel) { $row['sonids'] = GetSonIds($row['id'], 0, false); - if($row['sonids']=='') $row['rel'] = ''; - else $row['rel'] = " rel='dropmenu{$row['id']}'"; + if ($row['sonids'] == '') { + $row['rel'] = ''; + } else { + $row['rel'] = " rel='dropmenu{$row['id']}'"; + } + } //处理同级栏目中,当前栏目的样式 - if( ($row['id']==$typeid || ($topid==$row['id'] && $type=='top') ) && $currentstyle!='' ) - { + if (($row['id'] == $typeid || ($topid == $row['id'] && $type == 'top')) && $currentstyle != '') { $linkOkstr = $currentstyle; $row['typelink'] = GetOneTypeUrlA($row); - $linkOkstr = str_replace("~rel~",$row['rel'],$linkOkstr); - $linkOkstr = str_replace("~id~",$row['id'],$linkOkstr); - $linkOkstr = str_replace("~typelink~",$row['typelink'],$linkOkstr); - $linkOkstr = str_replace("~typename~",$row['typename'],$linkOkstr); + $linkOkstr = str_replace("~rel~", $row['rel'], $linkOkstr); + $linkOkstr = str_replace("~id~", $row['id'], $linkOkstr); + $linkOkstr = str_replace("~typelink~", $row['typelink'], $linkOkstr); + $linkOkstr = str_replace("~typename~", $row['typename'], $linkOkstr); $likeType .= $linkOkstr; - } - else - { + } else { $row['typelink'] = $row['typeurl'] = GetOneTypeUrlA($row); - if(is_array($dtp2->CTags)) - { - foreach($dtp2->CTags as $tagid=>$ctag) - { - if(isset($row[$ctag->GetName()])) $dtp2->Assign($tagid,$row[$ctag->GetName()]); + if (is_array($dtp2->CTags)) { + foreach ($dtp2->CTags as $tagid => $ctag) { + if (isset($row[$ctag->GetName()])) { + $dtp2->Assign($tagid, $row[$ctag->GetName()]); + } + } } $likeType .= $dtp2->GetResult(); } } - if($col>1) $likeType .= "
    \r\n"; + if ($col > 1) { + $likeType .= "
    \r\n"; + } + $GLOBALS['autoindex']++; } //Loop Col - if($col>1) - { + if ($col > 1) { $i += $col - 1; $likeType .= "
    \r\n"; } } //Loop for $i $dsql->FreeResult(); - if($cacheid !='') { + if ($cacheid != '') { WriteCacheBlock($cacheid, $likeType); } return $likeType; -} \ No newline at end of file +} diff --git a/include/taglib/channel/img.lib.php b/include/taglib/channel/img.lib.php index f352a1c6..9d93224c 100755 --- a/include/taglib/channel/img.lib.php +++ b/include/taglib/channel/img.lib.php @@ -1,8 +1,4 @@ -LoadSource($fvalue); - if(!is_array($dtp->CTags)) - { + if (!is_array($dtp->CTags)) { $dtp->Clear(); return "无图片信息!"; } @@ -30,16 +25,14 @@ function ch_img($fvalue,&$arcTag,&$refObj,$fname='') $row = $cfg_album_row; $icol = $cfg_album_col; $ptag = $dtp->GetTag('pagestyle'); - if(is_object($ptag)) - { + if (is_object($ptag)) { $pagestyle = $ptag->GetAtt('value'); $maxwidth = $ptag->GetAtt('maxwidth'); $ddmaxwidth = $ptag->GetAtt('ddmaxwidth'); $pagepicnum = $ptag->GetAtt('pagepicnum'); $irow = $ptag->GetAtt('row'); $icol = $ptag->GetAtt('col'); - if(empty($maxwidth)) - { + if (empty($maxwidth)) { $maxwidth = $cfg_album_width; } } @@ -49,30 +42,22 @@ function ch_img($fvalue,&$arcTag,&$refObj,$fname='') $mcol = 0; $images = array(); $innerTmp = $arcTag->GetInnerText(); - if(trim($innerTmp)=='') - { + if (trim($innerTmp) == '') { $innerTmp = GetSysTemplets("channel_article_image.htm"); } - if($pagestyle==1) - { + if ($pagestyle == 1) { $pagesize = $pagepicnum; - } - else if($pagestyle==2) - { + } else if ($pagestyle == 2) { $pagesize = 1; - } - else - { + } else { $pagesize = $irow * $icol; } - if(is_object($arcTag) && $arcTag->GetAtt('pagesize') > 0) - { + if (is_object($arcTag) && $arcTag->GetAtt('pagesize') > 0) { $pagesize = $arcTag->GetAtt('pagesize'); } - if(empty($pagesize)) - { + if (empty($pagesize)) { $pagesize = 12; } $aid = $refObj->ArcID; @@ -80,82 +65,66 @@ function ch_img($fvalue,&$arcTag,&$refObj,$fname='') $title = $row['title']; $revalue = ''; $GLOBAL['photoid'] = 0; - foreach($dtp->CTags as $ctag) - { - if($ctag->GetName()=="img") - { + foreach ($dtp->CTags as $ctag) { + if ($ctag->GetName() == "img") { $fields = $ctag->CAttribute->Items; - $fields['text'] = str_replace("'","",$ctag->GetAtt('text')); + $fields['text'] = str_replace("'", "", $ctag->GetAtt('text')); $fields['title'] = $title; $fields['imgsrc'] = trim($ctag->GetInnerText()); $fields['imgsrctrue'] = $fields['imgsrc']; - if(empty($fields['ddimg'])) - { + if (empty($fields['ddimg'])) { $fields['ddimg'] = $fields['imgsrc']; } - if($cfg_multi_site=='Y') - { + if ($cfg_multi_site == 'Y') { //$cfg_basehost) - if( !preg_match('#^http:#i', $fields['imgsrc']) ) { - $fields['imgsrc'] = $cfg_basehost.$fields['imgsrc']; + if (!preg_match('#^http:#i', $fields['imgsrc'])) { + $fields['imgsrc'] = $cfg_basehost . $fields['imgsrc']; } - if( !preg_match('#^http:#i', $fields['ddimg']) ) { - $fields['ddimg'] = $cfg_basehost.$fields['ddimg']; + if (!preg_match('#^http:#i', $fields['ddimg'])) { + $fields['ddimg'] = $cfg_basehost . $fields['ddimg']; } } - if(empty($fields['width'])) - { + if (empty($fields['width'])) { $fields['width'] = $maxwidth; } //if($fields['text']=='') //{ - //$fields['text'] = '图片'.($GLOBAL['photoid']+1); + //$fields['text'] = '图片'.($GLOBAL['photoid']+1); //} - $fields['alttext'] = str_replace("'",'',$fields['text']); + $fields['alttext'] = str_replace("'", '', $fields['text']); $fields['pagestyle'] = $pagestyle; $dtp2 = new DedeTagParse(); - $dtp2->SetNameSpace("field","[","]"); + $dtp2->SetNameSpace("field", "[", "]"); $dtp2->LoadSource($innerTmp); - if($GLOBAL['photoid']>0 && ($GLOBAL['photoid'] % $pagesize)==0) - { + if ($GLOBAL['photoid'] > 0 && ($GLOBAL['photoid'] % $pagesize) == 0) { $revalue .= "#p#分页标题#e#"; } - if($pagestyle==1) - { + if ($pagestyle == 1) { $fields['imgwidth'] = ''; $fields['linkurl'] = $fields['imgsrc']; $fields['textlink'] = "
    {$fields['text']}"; - } - else if($pagestyle==2) - { - if($fields['width'] > $maxwidth) { + } else if ($pagestyle == 2) { + if ($fields['width'] > $maxwidth) { $fields['imgwidth'] = " width='$maxwidth' "; - } - else { + } else { $fields['imgwidth'] = " width='{$fields['width']}' "; } $fields['linkurl'] = $fields['imgsrc']; - if($fields['text']!='') { + if ($fields['text'] != '') { $fields['textlink'] = "
    {$fields['text']}\r\n"; - } - else { + } else { $fields['textlink'] = ''; } - } - else if($pagestyle==3) - { + } else if ($pagestyle == 3) { $fields['text'] = $fields['textlink'] = ''; $fields['imgsrc'] = $fields['ddimg']; $fields['imgwidth'] = " width='$ddmaxwidth' "; - $fields['linkurl'] = "{$GLOBALS['cfg_phpurl']}/showphoto.php?aid={$refObj->ArcID}&src=".urlencode($fields['imgsrctrue'])."&npos={$GLOBAL['photoid']}"; + $fields['linkurl'] = "{$GLOBALS['cfg_phpurl']}/showphoto.php?aid={$refObj->ArcID}&src=" . urlencode($fields['imgsrctrue']) . "&npos={$GLOBAL['photoid']}"; } - if(is_array($dtp2->CTags)) - { - foreach($dtp2->CTags as $tagid=>$ctag) - { - if(isset($fields[$ctag->GetName()])) - { - $dtp2->Assign($tagid,$fields[$ctag->GetName()]); + if (is_array($dtp2->CTags)) { + foreach ($dtp2->CTags as $tagid => $ctag) { + if (isset($fields[$ctag->GetName()])) { + $dtp2->Assign($tagid, $fields[$ctag->GetName()]); } } $revalue .= $dtp2->GetResult(); @@ -164,4 +133,4 @@ function ch_img($fvalue,&$arcTag,&$refObj,$fname='') } } return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/channel/softlinks.lib.php b/include/taglib/channel/softlinks.lib.php index b696335f..a8e8bfec 100755 --- a/include/taglib/channel/softlinks.lib.php +++ b/include/taglib/channel/softlinks.lib.php @@ -1,5 +1,4 @@ -GetOne("SELECT * FROM `#@__softconfig` "); $phppath = $GLOBALS['cfg_phpurl']; $downlinks = ''; - if($row['downtype']!='0' && !$downloadpage) - { + if ($row['downtype'] != '0' && !$downloadpage) { $tempStr = GetSysTemplets("channel_downlinkpage.htm"); - $links = $phppath."/download.php?open=0&aid=".$refObj->ArcID."&cid=".$refObj->ChannelID; + $links = $phppath . "/download.php?open=0&aid=" . $refObj->ArcID . "&cid=" . $refObj->ChannelID; $downlinks = str_replace("~link~", $links, $tempStr); return $downlinks; - } - else - { + } else { return ch_softlinks_all($fvalue, $ctag, $refObj, $row); } } @@ -45,57 +41,63 @@ function ch_softlinks_all($fvalue, &$ctag, &$refObj, &$row) global $dsql, $cfg_phpurl; $phppath = $cfg_phpurl; $islinktype = false; - if(!empty($link_type)) $islinktype = true; + if (!empty($link_type)) { + $islinktype = true; + } + $dtp = new DedeTagParse(); $dtp->LoadSource($fvalue); - if( !is_array($dtp->CTags) ) - { + if (!is_array($dtp->CTags)) { $dtp->Clear(); return "无链接信息!"; } // 去除链接信息 - if (!empty($row['sites'])) - { + if (!empty($row['sites'])) { $sertype_arr = array(); $row['sites'] = preg_replace("#[\r\n]{1,}#", "\n", $row['sites']); $sites = explode("\n", trim($row['sites'])); - foreach($sites as $site) - { - if(trim($site)=='') continue; - list($link,$serverName,$serverType) = explode('|', $site); + foreach ($sites as $site) { + if (trim($site) == '') { + continue; + } + + list($link, $serverName, $serverType) = explode('|', $site); $sertype_arr[trim($serverName)] = trim($serverType); } } $tempStr = GetSysTemplets('channel_downlinks.htm'); $downlinks = ''; - foreach($dtp->CTags as $ctag) - { - if($ctag->GetName()=='link') - { + foreach ($dtp->CTags as $ctag) { + if ($ctag->GetName() == 'link') { $link = trim($ctag->GetInnerText()); $serverName = trim($ctag->GetAtt('text')); $islocal = trim($ctag->GetAtt('islocal')); - if (isset($sertype_arr[$serverName]) && $islinktype && $sertype_arr[$serverName] != $link_type) continue; - + if (isset($sertype_arr[$serverName]) && $islinktype && $sertype_arr[$serverName] != $link_type) { + continue; + } + //分析本地链接 - if(!isset($firstLink) && $islocal==1) $firstLink = $link; - if($islocal==1 && $row['islocal'] != 1) continue; - + if (!isset($firstLink) && $islocal == 1) { + $firstLink = $link; + } + + if ($islocal == 1 && $row['islocal'] != 1) { + continue; + } + //支持http,迅雷下载,ftp,flashget - if(!preg_match("#^http:\/\/|^thunder:\/\/|^ftp:\/\/|^flashget:\/\/#i", $link)) - { - $link = $GLOBALS['cfg_mainsite'].$link; + if (!preg_match("#^http:\/\/|^thunder:\/\/|^ftp:\/\/|^flashget:\/\/#i", $link)) { + $link = $GLOBALS['cfg_mainsite'] . $link; } $downloads = getDownloads($link); $uhash = substr(md5($link), 0, 24); - if($row['gotojump']==1) - { - $link = $phppath."/download.php?open=2&id={$refObj->ArcID}&uhash={$uhash}"; + if ($row['gotojump'] == 1) { + $link = $phppath . "/download.php?open=2&id={$refObj->ArcID}&uhash={$uhash}"; } - $temp = str_replace("~link~",$link,$tempStr); - $temp = str_replace("~server~",$serverName,$temp); - $temp = str_replace("~downloads~",$downloads,$temp); + $temp = str_replace("~link~", $link, $tempStr); + $temp = str_replace("~server~", $serverName, $temp); + $temp = str_replace("~downloads~", $downloads, $temp); $downlinks .= $temp; } } @@ -103,22 +105,24 @@ function ch_softlinks_all($fvalue, &$ctag, &$refObj, &$row) //获取镜像功能的地址 //必须设置为:[根据本地地址和服务器列表自动生成] 的情况 $linkCount = 1; - if($row['ismoresite']==1 && $row['moresitedo']==1 && trim($row['sites'])!='' && isset($firstLink)) - { + if ($row['ismoresite'] == 1 && $row['moresitedo'] == 1 && trim($row['sites']) != '' && isset($firstLink)) { $firstLink = preg_replace("#http:\/\/([^\/]*)\/#i", '/', $firstLink); - - foreach($sites as $site) - { - if(trim($site)=='') continue; - list($link,$serverName,$serverType) = explode('|', $site); - if (!empty($link_type) && $link_type != trim($serverType)) continue; - - $link = trim( preg_replace("#\/$#", "", $link) ).$firstLink; + + foreach ($sites as $site) { + if (trim($site) == '') { + continue; + } + + list($link, $serverName, $serverType) = explode('|', $site); + if (!empty($link_type) && $link_type != trim($serverType)) { + continue; + } + + $link = trim(preg_replace("#\/$#", "", $link)) . $firstLink; $downloads = getDownloads($link); $uhash = substr(md5($link), 0, 24); - if($row['gotojump']==1) - { - $link = $phppath."/download.php?open=2&id={$refObj->ArcID}&uhash={$uhash}"; + if ($row['gotojump'] == 1) { + $link = $phppath . "/download.php?open=2&id={$refObj->ArcID}&uhash={$uhash}"; } $temp = str_replace("~link~", $link, $tempStr); $temp = str_replace("~server~", $serverName, $temp); @@ -135,13 +139,10 @@ function getDownloads($url) $hash = md5($url); $query = "SELECT downloads FROM `#@__downloads` WHERE hash='$hash' "; $row = $dsql->GetOne($query); - if(is_array($row)) - { + if (is_array($row)) { $downloads = $row['downloads']; - } - else - { + } else { $downloads = 0; } return $downloads; -} \ No newline at end of file +} diff --git a/include/taglib/channel/specialtopic.lib.php b/include/taglib/channel/specialtopic.lib.php index 821c2867..ae71d9d1 100755 --- a/include/taglib/channel/specialtopic.lib.php +++ b/include/taglib/channel/specialtopic.lib.php @@ -1,4 +1,4 @@ -GetAtt('noteid'); $rvalue = ''; $tempStr = GetSysTemplets('channel_spec_note.htm'); $dtp = new DedeTagParse(); $dtp->LoadSource($noteinfo); - if(is_array($dtp->CTags)) - { - foreach($dtp->CTags as $k=>$ctag) - { + if (is_array($dtp->CTags)) { + foreach ($dtp->CTags as $k => $ctag) { $notename = $ctag->GetAtt('name'); //指定名称的专题节点 - if($noteid != '' && $ctag->GetAtt('noteid') != $noteid) - { + if ($noteid != '' && $ctag->GetAtt('noteid') != $noteid) { continue; } $isauto = $ctag->GetAtt('isauto'); @@ -33,30 +33,34 @@ function ch_specialtopic($noteinfo, $arcTag, $refObj, $fname='') $rownum = trim($ctag->GetAtt('rownum')); $keywords = ''; $stypeid = 0; - if(empty($rownum)) $rownum = 40; + if (empty($rownum)) { + $rownum = 40; + } //通过关键字和栏目ID自动获取模式 - if($isauto==1) - { + if ($isauto == 1) { $idlist = ''; $keywords = trim($ctag->GetAtt('keywords')); $stypeid = $ctag->GetAtt('typeid'); } - $listTemplet = trim($ctag->GetInnerText())!='' ? $ctag->GetInnerText() : GetSysTemplets('spec_arclist.htm'); - + $listTemplet = trim($ctag->GetInnerText()) != '' ? $ctag->GetInnerText() : GetSysTemplets('spec_arclist.htm'); + $idvalue = lib_arclistDone - ( - $refObj, $ctag, $stypeid, $rownum, $ctag->GetAtt('col'), $ctag->GetAtt('titlelen'),$ctag->GetAtt('infolen'), - $ctag->GetAtt('imgwidth'), $ctag->GetAtt('imgheight'), 'all', 'default', $keywords, $listTemplet, 0, $idlist, - $ctag->GetAtt('channel'), '', $ctag->GetAtt('att') - ); + ( + $refObj, $ctag, $stypeid, $rownum, $ctag->GetAtt('col'), $ctag->GetAtt('titlelen'), $ctag->GetAtt('infolen'), + $ctag->GetAtt('imgwidth'), $ctag->GetAtt('imgheight'), 'all', 'default', $keywords, $listTemplet, 0, $idlist, + $ctag->GetAtt('channel'), '', $ctag->GetAtt('att') + ); $notestr = str_replace('~notename~', $notename, $tempStr); $notestr = str_replace('~spec_arclist~', $idvalue, $notestr); $rvalue .= $notestr; - if($noteid != '' && $ctag->GetAtt('noteid')==$noteid) break; + if ($noteid != '' && $ctag->GetAtt('noteid') == $noteid) { + break; + } + } } $dtp->Clear(); return $rvalue; -} \ No newline at end of file +} diff --git a/include/taglib/channel/stepselect.lib.php b/include/taglib/channel/stepselect.lib.php index 8aff3a11..909517cf 100755 --- a/include/taglib/channel/stepselect.lib.php +++ b/include/taglib/channel/stepselect.lib.php @@ -1,9 +1,8 @@ -=500) - { - if($evalue % 500 == 0) - { - return (isset($GLOBALS['em_'.$egroup.'s'][$evalue]) ? $GLOBALS['em_'.$egroup.'s'][$evalue] : ''); - } - else if (preg_match("#([0-9]{1,})\.([0-9]{1,})#", $evalue, $matchs)) - { + if ($evalue >= 500) { + if ($evalue % 500 == 0) { + return (isset($GLOBALS['em_' . $egroup . 's'][$evalue]) ? $GLOBALS['em_' . $egroup . 's'][$evalue] : ''); + } else if (preg_match("#([0-9]{1,})\.([0-9]{1,})#", $evalue, $matchs)) { $esonvalue = $matchs[1]; $etopvalue = $esonvalue - ($esonvalue % 500); $esecvalue = $evalue; - $GLOBALS['em_'.$egroup.'s'][$etopvalue] = empty($GLOBALS['em_'.$egroup.'s'][$etopvalue])? '' - : $GLOBALS['em_'.$egroup.'s'][$etopvalue]; - $GLOBALS['em_'.$egroup.'s'][$esonvalue] = empty($GLOBALS['em_'.$egroup.'s'][$esonvalue])? '' - : $GLOBALS['em_'.$egroup.'s'][$esonvalue]; - $GLOBALS['em_'.$egroup.'s'][$esecvalue] = empty($GLOBALS['em_'.$egroup.'s'][$esecvalue])? '' - : $GLOBALS['em_'.$egroup.'s'][$esecvalue]; - return $GLOBALS['em_'.$egroup.'s'][$etopvalue].' -- '.$GLOBALS['em_'.$egroup.'s'][$esonvalue].' -- '.$GLOBALS['em_'.$egroup.'s'][$esecvalue]; - } - else - { + $GLOBALS['em_' . $egroup . 's'][$etopvalue] = empty($GLOBALS['em_' . $egroup . 's'][$etopvalue]) ? '' + : $GLOBALS['em_' . $egroup . 's'][$etopvalue]; + $GLOBALS['em_' . $egroup . 's'][$esonvalue] = empty($GLOBALS['em_' . $egroup . 's'][$esonvalue]) ? '' + : $GLOBALS['em_' . $egroup . 's'][$esonvalue]; + $GLOBALS['em_' . $egroup . 's'][$esecvalue] = empty($GLOBALS['em_' . $egroup . 's'][$esecvalue]) ? '' + : $GLOBALS['em_' . $egroup . 's'][$esecvalue]; + return $GLOBALS['em_' . $egroup . 's'][$etopvalue] . ' -- ' . $GLOBALS['em_' . $egroup . 's'][$esonvalue] . ' -- ' . $GLOBALS['em_' . $egroup . 's'][$esecvalue]; + } else { $elimit = $evalue % 500; $erevalue = $evalue - $elimit; - $GLOBALS['em_'.$egroup.'s'][$erevalue] = empty($GLOBALS['em_'.$egroup.'s'][$erevalue])? '' - : $GLOBALS['em_'.$egroup.'s'][$erevalue]; - $GLOBALS['em_'.$egroup.'s'][$evalue] = empty($GLOBALS['em_'.$egroup.'s'][$evalue])? '' - : $GLOBALS['em_'.$egroup.'s'][$evalue]; - return $GLOBALS['em_'.$egroup.'s'][$erevalue].' -- '.$GLOBALS['em_'.$egroup.'s'][$evalue]; + $GLOBALS['em_' . $egroup . 's'][$erevalue] = empty($GLOBALS['em_' . $egroup . 's'][$erevalue]) ? '' + : $GLOBALS['em_' . $egroup . 's'][$erevalue]; + $GLOBALS['em_' . $egroup . 's'][$evalue] = empty($GLOBALS['em_' . $egroup . 's'][$evalue]) ? '' + : $GLOBALS['em_' . $egroup . 's'][$evalue]; + return $GLOBALS['em_' . $egroup . 's'][$erevalue] . ' -- ' . $GLOBALS['em_' . $egroup . 's'][$evalue]; } } -} \ No newline at end of file +} diff --git a/include/taglib/channelartlist.lib.php b/include/taglib/channelartlist.lib.php index abc6f9d8..004cfa1f 100755 --- a/include/taglib/channelartlist.lib.php +++ b/include/taglib/channelartlist.lib.php @@ -1,4 +1,4 @@ - {dede:channelartlist row=6}
    -
    {dede:field name='typename'/}
    -
    - {dede:arclist titlelen='42' row='10'} +
    {dede:field name='typename'/}
    +
    +{dede:arclist titlelen='42' row='10'} {/dede:arclist}
    {/dede:channelartlist} - typeid:频道ID - row:获取的栏目返回值 - +typeid:频道ID +row:获取的栏目返回值 + >>dede>>*/ - -require_once(DEDEINC.'/arc.partview.class.php'); -function lib_channelartlist(&$ctag,&$refObj) +require_once DEDEINC . '/arc.partview.class.php'; + +function lib_channelartlist(&$ctag, &$refObj) { - global $dsql,$envs,$_sys_globals; + global $dsql, $envs, $_sys_globals; //处理标记属性、innertext $attlist = 'typeid|0,row|20,cacheid|'; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $innertext = trim($ctag->GetInnerText()); $artlist = ''; //读取固定的缓存块 $cacheid = trim($cacheid); - if($cacheid !='') { + if ($cacheid != '') { $artlist = GetCacheBlock($cacheid); - if($artlist!='') return $artlist; + if ($artlist != '') { + return $artlist; + } + } - - if(empty($typeid)) - { - $typeid = ( !empty($refObj->TypeLink->TypeInfos['id']) ? $refObj->TypeLink->TypeInfos['id'] : 0 ); + + if (empty($typeid)) { + $typeid = (!empty($refObj->TypeLink->TypeInfos['id']) ? $refObj->TypeLink->TypeInfos['id'] : 0); + } + + if ($innertext == '') { + $innertext = GetSysTemplets('part_channelartlist.htm'); } - - if($innertext=='') $innertext = GetSysTemplets('part_channelartlist.htm'); + $totalnum = $row; - if(empty($totalnum)) $totalnum = 20; + if (empty($totalnum)) { + $totalnum = 20; + } //获得类别ID总数的信息 $typeids = array(); - if($typeid==0 || $typeid=='top') { + if ($typeid == 0 || $typeid == 'top') { $tpsql = " reid=0 AND ispart<>2 AND ishidden<>1 AND channeltype>0 "; - } - else - { - if(!preg_match('#,#', $typeid)) { + } else { + if (!preg_match('#,#', $typeid)) { $tpsql = " reid='$typeid' AND ispart<>2 AND ishidden<>1 "; - } - else { + } else { $tpsql = " id IN($typeid) AND ispart<>2 AND ishidden<>1 "; } } - $dsql->SetQuery("SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath + $dsql->SetQuery("SELECT id,typename,typedir,isdefault,ispart,defaultname,namerule2,moresite,siteurl,sitepath FROM `#@__arctype` WHERE $tpsql ORDER BY sortrank ASC LIMIT $totalnum"); $dsql->Execute(); - while($row = $dsql->GetArray()) { + while ($row = $dsql->GetArray()) { $typeids[] = $row; } - if(!isset($typeids[0])) return ''; + if (!isset($typeids[0])) { + return ''; + } $GLOBALS['itemindex'] = 0; $GLOBALS['itemparity'] = 1; - for($i=0;isset($typeids[$i]);$i++) - { + for ($i = 0;isset($typeids[$i]); $i++) { $GLOBALS['itemindex']++; $pv = new PartView($typeids[$i]['id']); $pv->Fields['typeurl'] = GetOneTypeUrlA($typeids[$i]); - $pv->SetTemplet($innertext,'string'); + $pv->SetTemplet($innertext, 'string'); $artlist .= $pv->GetResult(); - $GLOBALS['itemparity'] = ($GLOBALS['itemparity']==1 ? 2 : 1); + $GLOBALS['itemparity'] = ($GLOBALS['itemparity'] == 1 ? 2 : 1); } //注销环境变量,以防止后续调用中被使用 $GLOBALS['envs']['typeid'] = $_sys_globals['typeid']; $GLOBALS['envs']['reid'] = ''; - if($cacheid !='') { + if ($cacheid != '') { WriteCacheBlock($cacheid, $artlist); } return $artlist; -} \ No newline at end of file +} diff --git a/include/taglib/demotag.lib.php b/include/taglib/demotag.lib.php index 4c8d4aed..7ad719d8 100755 --- a/include/taglib/demotag.lib.php +++ b/include/taglib/demotag.lib.php @@ -1,7 +1,4 @@ ->dede>> 演示标签 全局标记 @@ -21,24 +18,24 @@ {dede:demotag /} - + >>dede>>*/ - -function lib_demotag(&$ctag,&$refObj) + +function lib_demotag(&$ctag, &$refObj) { - global $dsql,$envs; - + global $dsql, $envs; + //属性处理 - $attlist="row|12,titlelen|24"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "row|12,titlelen|24"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $revalue = ''; - + //你需编写的代码,不能用echo之类语法,把最终返回值传给$revalue //------------------------------------------------------ - + $revalue = 'Hello Word!'; - + //------------------------------------------------------ return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/feedback.lib.php b/include/taglib/feedback.lib.php index 44003e45..1d407aed 100755 --- a/include/taglib/feedback.lib.php +++ b/include/taglib/feedback.lib.php @@ -1,8 +1,4 @@ ->dede>> 会员评论内容 全局标记 @@ -20,48 +16,44 @@ 用于调用最新评论 {dede:feedback} -
      -
    • [field:username function="(@me=='guest' ? '游客' : @me)"/] 对 [field:title/] 的评论:
    • -
    • [field:msg /]
    • -
    +
      +
    • [field:username function="(@me=='guest' ? '游客' : @me)"/] 对 [field:title/] 的评论:
    • +
    • [field:msg /]
    • +
    {/dede:feedback}
    - row:调用评论条数 - titlelen:标题长度 - infolen:评论长度 - +row:调用评论条数 +titlelen:标题长度 +infolen:评论长度 + >>dede>>*/ - -function lib_feedback(&$ctag,&$refObj) + +function lib_feedback(&$ctag, &$refObj) { global $dsql; - $attlist="row|12,titlelen|24,infolen|100"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "row|12,titlelen|24,infolen|100"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $innertext = trim($ctag->GetInnerText()); $totalrow = $row; $revalue = ''; - if(empty($innertext)) - { + if (empty($innertext)) { $innertext = GetSysTemplets('tag_feedback.htm'); } $wsql = " where ischeck=1 "; $equery = "SELECT * FROM `#@__feedback` $wsql ORDER BY id DESC LIMIT 0 , $totalrow"; $ctp = new DedeTagParse(); - $ctp->SetNameSpace('field','[',']'); + $ctp->SetNameSpace('field', '[', ']'); $ctp->LoadSource($innertext); - $dsql->Execute('fb',$equery); - while($arr=$dsql->GetArray('fb')) - { - $arr['title'] = cn_substr($arr['arctitle'],$titlelen); - $arr['msg'] = jsTrim(Html2Text($arr['msg']),$infolen); - foreach($ctp->CTags as $tagid=>$ctag) - { - if(!empty($arr[$ctag->GetName()])) - { - $ctp->Assign($tagid,$arr[$ctag->GetName()]); + $dsql->Execute('fb', $equery); + while ($arr = $dsql->GetArray('fb')) { + $arr['title'] = cn_substr($arr['arctitle'], $titlelen); + $arr['msg'] = jsTrim(Html2Text($arr['msg']), $infolen); + foreach ($ctp->CTags as $tagid => $ctag) { + if (!empty($arr[$ctag->GetName()])) { + $ctp->Assign($tagid, $arr[$ctag->GetName()]); } } $revalue .= $ctp->GetResult(); @@ -69,11 +61,11 @@ function lib_feedback(&$ctag,&$refObj) return $revalue; } -function jsTrim($str,$len) +function jsTrim($str, $len) { - $str = preg_replace("/{quote}(.*){\/quote}/is",'',$str); - $str = str_replace('<br/>',' ',$str); - $str = cn_substr($str,$len); + $str = preg_replace("/{quote}(.*){\/quote}/is", '', $str); + $str = str_replace('<br/>', ' ', $str); + $str = cn_substr($str, $len); $str = preg_replace("#['\"\r\n]#", "", $str); return $str; -} \ No newline at end of file +} diff --git a/include/taglib/flink.lib.php b/include/taglib/flink.lib.php index 451aec9e..d6d56324 100755 --- a/include/taglib/flink.lib.php +++ b/include/taglib/flink.lib.php @@ -1,8 +1,4 @@ - - type:链接类型 - row:链接数量 - titlelen:站点文字的长度 - linktype:链接位置内页 - typeid:所有类型,可以在系统后台[模块]-[友情链接]中的“网站类型管理”中查看 - +type:链接类型 +row:链接数量 +titlelen:站点文字的长度 +linktype:链接位置内页 +typeid:所有类型,可以在系统后台[模块]-[友情链接]中的“网站类型管理”中查看 + >>dede>>*/ helper('cache'); -function lib_flink(&$ctag,&$refObj) +function lib_flink(&$ctag, &$refObj) { - - global $dsql,$cfg_soft_lang; - $attlist="type|textall,row|24,titlelen|24,linktype|1,typeid|0"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + + global $dsql, $cfg_soft_lang; + $attlist = "type|textall,row|24,titlelen|24,linktype|1,typeid|0"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $totalrow = $row; $revalue = ''; - if (isset($GLOBALS['envs']['flinkid'])) - { + if (isset($GLOBALS['envs']['flinkid'])) { $typeid = $GLOBALS['envs']['flinkid']; } $wsql = " where ischeck >= '$linktype' "; - - if($typeid == 0) - { + + if ($typeid == 0) { $wsql .= ''; - } - else if($typeid == 999) - { - $prefix = 'flink'; - $key = '999'; - $row = GetCache($prefix, $key); - - if(!is_array($row)) - { - require (DEDEDATA.'/admin/config_update.php'); - if (!class_exists('DedeHttpDown', false)) { - require_once(DEDEINC.'/dedehttpdown.class.php'); - } - $del = new DedeHttpDown(); - if ( defined( 'LINKHOST' ) ) $linkHost = LINKHOST; - else $linkHost = 'http://flink.dedecms.com/server_url.php'; - $del->OpenUrl($linkHost); - $linkUrl = $del->GetHtml()."flink.php?lang={$cfg_soft_lang}&site={$_SERVER['SERVER_NAME']}"; - $del->OpenUrl($linkUrl); - $linkInfo = $del->GetHtml(); - - if(!empty($linkInfo)){ - $dedelink = explode("\t", $linkInfo); - for($i=0; $i".@$dedelink[$i].""; - } - } - } else { - $revalue=<<OpenUrl($linkHost); + $linkUrl = $del->GetHtml() . "flink.php?lang={$cfg_soft_lang}&site={$_SERVER['SERVER_NAME']}"; + $del->OpenUrl($linkUrl); + $linkInfo = $del->GetHtml(); + + if (!empty($linkInfo)) { + $dedelink = explode("\t", $linkInfo); + for ($i = 0; $i < count($dedelink); $i++) { + if ($i % 5 == 0 && $i != count($dedelink)) { + $revalue .= "
  • " . @$dedelink[$i] . "
  • "; + } + } + } else { + $revalue = <<DedeCMS广告
  • 织梦客户服务中心
  • 织梦问答
  • @@ -87,60 +82,49 @@ function lib_flink(&$ctag,&$refObj) 织梦CMS帮助中心
  • EOT; - } - $row['reval'] = $revalue; - SetCache($prefix, $key, $row, 60*60*1); - } - - return $row['reval']; - } - else - { + } + $row['reval'] = $revalue; + SetCache($prefix, $key, $row, 60 * 60 * 1); + } + + return $row['reval']; + } else { $wsql .= "And typeid = '$typeid'"; } - if($type=='image') - { + if ($type == 'image') { $wsql .= " And logo<>'' "; - } - else if($type=='text') - { + } else if ($type == 'text') { $wsql .= " And logo='' "; } $equery = "SELECT * FROM #@__flink $wsql order by sortrank asc limit 0,$totalrow"; - if(trim($ctag->GetInnerText())=='') $innertext = "
  • [field:link /]
  • "; - else $innertext = $ctag->GetInnerText(); - + if (trim($ctag->GetInnerText()) == '') { + $innertext = "
  • [field:link /]
  • "; + } else { + $innertext = $ctag->GetInnerText(); + } + $dsql->SetQuery($equery); $dsql->Execute(); - - while($dbrow=$dsql->GetObject()) - { - if($type=='text'||$type=='textall') - { - $link = "".cn_substr($dbrow->webname,$titlelen)." "; - } - else if($type=='image') - { - $link = " "; - } - else - { - if($dbrow->logo=='') - { - $link = "".cn_substr($dbrow->webname,$titlelen)." "; - } - else - { - $link = " "; + + while ($dbrow = $dsql->GetObject()) { + if ($type == 'text' || $type == 'textall') { + $link = "" . cn_substr($dbrow->webname, $titlelen) . " "; + } else if ($type == 'image') { + $link = " "; + } else { + if ($dbrow->logo == '') { + $link = "" . cn_substr($dbrow->webname, $titlelen) . " "; + } else { + $link = " "; } } $rbtext = preg_replace("/\[field:url([\/\s]{0,})\]/isU", $row['url'], $innertext); - $rbtext = preg_replace("/\[field:webname([\/\s]{0,})\]/isU", $row['webname'], $rbtext); - $rbtext = preg_replace("/\[field:logo([\/\s]{0,})\]/isU", $row['logo'], $rbtext); - $rbtext = preg_replace("/\[field:link([\/\s]{0,})\]/isU", $link, $rbtext); - $revalue .= $rbtext; + $rbtext = preg_replace("/\[field:webname([\/\s]{0,})\]/isU", $row['webname'], $rbtext); + $rbtext = preg_replace("/\[field:logo([\/\s]{0,})\]/isU", $row['logo'], $rbtext); + $rbtext = preg_replace("/\[field:link([\/\s]{0,})\]/isU", $link, $rbtext); + $revalue .= $rbtext; } return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/flinktype.lib.php b/include/taglib/flinktype.lib.php index c694708b..40d9dfcd 100755 --- a/include/taglib/flinktype.lib.php +++ b/include/taglib/flinktype.lib.php @@ -1,9 +1,4 @@ - - row:链接类型数量 - titlelen:链接文字的长度 - +row:链接类型数量 +titlelen:链接文字的长度 + >>dede>>*/ - -function lib_flinktype(&$ctag,&$refObj) +require_once DEDEINC . "/taglib/flink.lib.php"; + +function lib_flinktype(&$ctag, &$refObj) { global $dsql; - $attlist="row|24,titlelen|24"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "row|24,titlelen|24"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $totalrow = $row; $revalue = ''; - + $equery = "SELECT * FROM #@__flinktype order by id asc limit 0,$totalrow"; - if(trim($ctag->GetInnerText())=='') $innertext = "
  • [field:typename /]
  • "; - else $innertext = $ctag->GetInnerText(); - if(!isset($type)) $type = ''; + if (trim($ctag->GetInnerText()) == '') { + $innertext = "
  • [field:typename /]
  • "; + } else { + $innertext = $ctag->GetInnerText(); + } + + if (!isset($type)) { + $type = ''; + } + $dtp = new DedeTagParse(); - $dtp->SetNameSpace("dede","{","}"); + $dtp->SetNameSpace("dede", "{", "}"); $dtp->LoadString($innertext); - + $dsql->SetQuery($equery); $dsql->Execute(); $rs = ''; $row = array(); - while($dbrow=$dsql->GetObject()) - { + while ($dbrow = $dsql->GetObject()) { $row[] = $dbrow; } - $dedecms = false; - $dedecms->id = 999; - $dedecms->typename = '织梦链'; - if($type == 'dedecms') $row[] = $dedecms; - + $dedecms = false; + $dedecms->id = 999; + $dedecms->typename = '织梦链'; + if ($type == 'dedecms') { + $row[] = $dedecms; + } + foreach ($row as $key => $value) { - if (is_array($dtp->CTags)) - { + if (is_array($dtp->CTags)) { $GLOBALS['envs']['flinkid'] = $value->id; - foreach($dtp->CTags as $tagid=>$ctag) - { + foreach ($dtp->CTags as $tagid => $ctag) { $tagname = $ctag->GetName(); - if($tagname=="flink") $dtp->Assign($tagid, lib_flink($ctag, $refObj)); + if ($tagname == "flink") { + $dtp->Assign($tagid, lib_flink($ctag, $refObj)); + } + } } $rs = $dtp->GetResult(); - $rs = preg_replace("/\[field:id([\/\s]{0,})\]/isU", $value->id, $rs); + $rs = preg_replace("/\[field:id([\/\s]{0,})\]/isU", $value->id, $rs); $rs = preg_replace("/\[field:typename([\/\s]{0,})\]/isU", $value->typename, $rs); $revalue .= $rs; } - + return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/group.lib.php b/include/taglib/group.lib.php index eca9076a..35a999bd 100755 --- a/include/taglib/group.lib.php +++ b/include/taglib/group.lib.php @@ -1,4 +1,4 @@ ->dede>> 圈子标签 全局标记 @@ -16,53 +16,58 @@ 圈子调用标签 {dede:group row='6' orderby='threads' titlelen='30'} -
  • - - [field:groupname/] -
  • -{/dede:group} +
  • + +[field:groupname/] +
  • +{/dede:group}
    - row:调用条数 - orderby:排列顺序(默认是主题数) - titlelen:圈子名称最大长度 - +row:调用条数 +orderby:排列顺序(默认是主题数) +titlelen:圈子名称最大长度 + >>dede>>*/ - -function lib_group(&$ctag,&$refObj) + +function lib_group(&$ctag, &$refObj) { global $dsql, $envs, $cfg_dbprefix, $cfg_cmsurl; //属性处理 - $attlist="row|6,orderby|threads,titlelen|30"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "row|6,orderby|threads,titlelen|30"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - if( !$dsql->IsTable("{$cfg_dbprefix}groups") ) return '没安装圈子模块'; - - if(!preg("#\/$#", $cfg_cmsurl)) $cfg_group_url = $cfg_cmsurl.'/group'; - else $cfg_group_url = $cfg_cmsurl.'group'; - + if (!$dsql->IsTable("{$cfg_dbprefix}groups")) { + return '没安装圈子模块'; + } + + if (!preg("#\/$#", $cfg_cmsurl)) { + $cfg_group_url = $cfg_cmsurl . '/group'; + } else { + $cfg_group_url = $cfg_cmsurl . 'group'; + } + $innertext = $ctag->GetInnerText(); - if(trim($innertext)=='') $innertext = GetSysTemplets("groups.htm"); - + if (trim($innertext) == '') { + $innertext = GetSysTemplets("groups.htm"); + } + $list = ''; $dsql->SetQuery("SELECT groupimg,groupid,groupname FROM `#@__groups` WHERE ishidden=0 ORDER BY $orderby DESC LIMIT 0,{$row}"); $dsql->Execute(); $ctp = new DedeTagParse(); $ctp->SetNameSpace('field', '[', ']'); - while($rs = $dsql->GetArray()) - { + while ($rs = $dsql->GetArray()) { $ctp->LoadSource($innertext); $rs['groupname'] = cn_substr($rs['groupname'], $titlelen); - $rs['url'] = $cfg_group_url."/group.php?id={$rs['groupid']}"; - $rs['icon'] = $rs['groupimg']; - foreach($ctp->CTags as $tagid=>$ctag) - { - if( !empty($rs[strtolower($ctag->GetName())]) ) { - $ctp->Assign($tagid,$rs[$ctag->GetName()]); + $rs['url'] = $cfg_group_url . "/group.php?id={$rs['groupid']}"; + $rs['icon'] = $rs['groupimg']; + foreach ($ctp->CTags as $tagid => $ctag) { + if (!empty($rs[strtolower($ctag->GetName())])) { + $ctp->Assign($tagid, $rs[$ctag->GetName()]); } - } - $list .= $ctp->GetResult(); + } + $list .= $ctp->GetResult(); } return $list; -} \ No newline at end of file +} diff --git a/include/taglib/groupthread.lib.php b/include/taglib/groupthread.lib.php index 60b01845..80aaa024 100755 --- a/include/taglib/groupthread.lib.php +++ b/include/taglib/groupthread.lib.php @@ -1,4 +1,4 @@ ->dede>> 圈子主题 全局标记 @@ -16,63 +16,73 @@ 圈子主题调用标签 {dede:groupthread gid='0' orderby='dateline' orderway='desc' row='12' titlelen='30'} -
  • - [[field:groupname function="cn_substr(@me,10)"/]] - [field:subject/]([field:lastpost function="GetDateMk('@me')"/]) -
  • -{/dede:groupthread} +
  • +[[field:groupname function="cn_substr(@me,10)"/]] +[field:subject/]([field:lastpost function="GetDateMk('@me')"/]) +
  • +{/dede:groupthread}
    - gid:圈子id,默认为全部 - orderby:排序,默认为时间 - orderway:排序方向,默认是最新主题在前 - row:记录数 - titlelen:主题标题(subject)最大长度 - +gid:圈子id,默认为全部 +orderby:排序,默认为时间 +orderway:排序方向,默认是最新主题在前 +row:记录数 +titlelen:主题标题(subject)最大长度 + >>dede>>*/ - -function lib_groupthread(&$ctag,&$refObj) + +function lib_groupthread(&$ctag, &$refObj) { global $dsql, $envs, $cfg_dbprefix, $cfg_cmsurl; //属性处理 - $attlist="gid|0,orderby|dateline,orderway|desc,row|12,titlelen|30"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "gid|0,orderby|dateline,orderway|desc,row|12,titlelen|30"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - - if( !$dsql->IsTable("{$cfg_dbprefix}groups") ) return '没安装圈子模块'; - if(!preg_match("#\/$#", $cfg_cmsurl)) $cfg_group_url = $cfg_cmsurl."/group"; - else $cfg_group_url = $cfg_cmsurl."group"; - + if (!$dsql->IsTable("{$cfg_dbprefix}groups")) { + return '没安装圈子模块'; + } + + if (!preg_match("#\/$#", $cfg_cmsurl)) { + $cfg_group_url = $cfg_cmsurl . "/group"; + } else { + $cfg_group_url = $cfg_cmsurl . "group"; + } + $innertext = $ctag->GetInnerText(); - if(trim($innertext)=='') $innertext = GetSysTemplets('groupthreads.htm'); - + if (trim($innertext) == '') { + $innertext = GetSysTemplets('groupthreads.htm'); + } + $WhereSql = " WHERE t.closed=0 "; - $orderby = 't.'.$orderby; - if($gid > 0) $WhereSql .= " AND t.gid='$gid' "; - - $query = "SELECT t.subject,t.gid,t.tid,t.lastpost,g.groupname FROM `#@__group_threads` t + $orderby = 't.' . $orderby; + if ($gid > 0) { + $WhereSql .= " AND t.gid='$gid' "; + } + + $query = "SELECT t.subject,t.gid,t.tid,t.lastpost,g.groupname FROM `#@__group_threads` t LEFT JOIN `#@__groups` g ON g.groupid=t.gid $WhereSql ORDER BY $orderby $orderway LIMIT 0,{$row}"; - + $dsql->SetQuery($query); $dsql->Execute(); $ctp = new DedeTagParse(); $ctp->SetNameSpace('field', '[', ']'); - if(!isset($list)) $list = ''; - while($rs = $dsql->GetArray()) - { + if (!isset($list)) { + $list = ''; + } + + while ($rs = $dsql->GetArray()) { $ctp->LoadSource($innertext); $rs['subject'] = cn_substr($rs['subject'], $titlelen); - $rs['url'] = $cfg_group_url."/viewthread.php?id={$rs['gid']}&tid={$rs['tid']}"; - $rs['groupurl'] = $cfg_group_url."/group.php?id={$rs['gid']}"; - foreach($ctp->CTags as $tagid=>$ctag) { - if(!empty($rs[strtolower($ctag->GetName())])) - { - $ctp->Assign($tagid, $rs[$ctag->GetName()]); + $rs['url'] = $cfg_group_url . "/viewthread.php?id={$rs['gid']}&tid={$rs['tid']}"; + $rs['groupurl'] = $cfg_group_url . "/group.php?id={$rs['gid']}"; + foreach ($ctp->CTags as $tagid => $ctag) { + if (!empty($rs[strtolower($ctag->GetName())])) { + $ctp->Assign($tagid, $rs[$ctag->GetName()]); } - } - $list .= $ctp->GetResult(); + } + $list .= $ctp->GetResult(); } return $list; -} \ No newline at end of file +} diff --git a/include/taglib/hotwords.lib.php b/include/taglib/hotwords.lib.php index ac75c4bc..29bafc87 100755 --- a/include/taglib/hotwords.lib.php +++ b/include/taglib/hotwords.lib.php @@ -8,7 +8,7 @@ * @license http://help.dedecms.com/usersguide/license.html * @link http://www.dedecms.com */ - + /*>>dede>> 热门关键词 全局标记 @@ -18,31 +18,40 @@ {dede:hotwords /} - num:关键词数目 - subday:天数 - maxlength:关键词最大长度 - +num:关键词数目 +subday:天数 +maxlength:关键词最大长度 + >>dede>>*/ - -function lib_hotwords(&$ctag,&$refObj) + +function lib_hotwords(&$ctag, &$refObj) { - global $cfg_phpurl,$dsql; + global $cfg_phpurl, $dsql; - $attlist="num|6,subday|365,maxlength|16"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "num|6,subday|365,maxlength|16"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $nowtime = time(); - if(empty($subday)) $subday = 365; - if(empty($num)) $num = 6; - if(empty($maxlength)) $maxlength = 20; - $maxlength = $maxlength+1; + if (empty($subday)) { + $subday = 365; + } + + if (empty($num)) { + $num = 6; + } + + if (empty($maxlength)) { + $maxlength = 20; + } + + $maxlength = $maxlength + 1; $mintime = $nowtime - ($subday * 24 * 3600); $dsql->SetQuery("SELECT keyword FROM `#@__search_keywords` WHERE lasttime>$mintime AND length(keyword)<$maxlength ORDER BY count DESC LIMIT 0,$num"); $dsql->Execute('hw'); $hotword = ''; - while($row=$dsql->GetArray('hw')){ - $hotword .= " ".$row['keyword']." "; + while ($row = $dsql->GetArray('hw')) { + $hotword .= " " . $row['keyword'] . " "; } return $hotword; -} \ No newline at end of file +} diff --git a/include/taglib/infoguide.lib.php b/include/taglib/infoguide.lib.php index 6afa41ca..600b4b4d 100755 --- a/include/taglib/infoguide.lib.php +++ b/include/taglib/infoguide.lib.php @@ -1,4 +1,4 @@ ->dede>> + +/*>>dede>> 分类信息搜索 全局标记 V55,V56,V57 @@ -18,77 +18,78 @@ {dede:infoguide /} - + >>dede>>*/ - -function lib_infoguide(&$ctag,&$refObj) + +function lib_infoguide(&$ctag, &$refObj) { - global $dsql,$nativeplace,$infotype,$hasSetEnumJs,$cfg_cmspath,$cfg_mainsite; - + global $dsql, $nativeplace, $infotype, $hasSetEnumJs, $cfg_cmspath, $cfg_mainsite; + //属性处理 //$attlist="row|12,titlelen|24"; //FillAttsDefault($ctag->CAttribute->Items,$attlist); //extract($ctag->CAttribute->Items, EXTR_SKIP); - - $cmspath = ( (empty($cfg_cmspath) || preg_match('#[/$]#', $cfg_cmspath)) ? $cfg_cmspath.'/' : $cfg_cmspath ); - - if(empty($refObj->Fields['typeid'])) - { + + $cmspath = ((empty($cfg_cmspath) || preg_match('#[/$]#', $cfg_cmspath)) ? $cfg_cmspath . '/' : $cfg_cmspath); + + if (empty($refObj->Fields['typeid'])) { $row = $dsql->GetOne("SELECT id FROM `#@__arctype` WHERE channeltype='-8' And reid = '0' "); $typeid = (is_array($row) ? $row['id'] : 0); - if(empty($typeid)) - { + if (empty($typeid)) { return '请指定一个栏目类型为“分类信息”,否则无法使用这个搜索表单!'; } - } - else - { + } else { $typeid = $refObj->Fields['typeid']; } - + $innerText = trim($ctag->GetInnerText()); - if(empty($innerText)) $innerText = GetSysTemplets("info_guide.htm"); + if (empty($innerText)) { + $innerText = GetSysTemplets("info_guide.htm"); + } + $ctp = new DedeTagParse(); - $ctp->SetNameSpace('field','[',']'); + $ctp->SetNameSpace('field', '[', ']'); $ctp->LoadSource($innerText); $revalue = $seli = ''; - - $fields = array('nativeplace'=>'','infotype'=>'','typeid'=>$typeid); - - if($hasSetEnumJs !='has' ) - { - $revalue .= ''."\r\n"; + + $fields = array('nativeplace' => '', 'infotype' => '', 'typeid' => $typeid); + + if ($hasSetEnumJs != 'has') { + $revalue .= '' . "\r\n"; $GLOBALS['hasSetEnumJs'] = 'hasset'; } - + $fields['nativeplace'] = $fields['infotype'] = ''; - - if(empty($nativeplace)) $nativeplace = 0; - if(empty($infotype)) $infotype = 0; - + + if (empty($nativeplace)) { + $nativeplace = 0; + } + + if (empty($infotype)) { + $infotype = 0; + } + $fields['nativeplace'] .= "\r\n"; $fields['nativeplace'] .= "地区:\r\n"; $fields['nativeplace'] .= "\r\n
    \r\n"; $fields['nativeplace'] .= "\r\n"; - $fields['nativeplace'] .= ''."\r\n"; - + $fields['nativeplace'] .= '' . "\r\n"; + $fields['infotype'] .= "\r\n"; $fields['infotype'] .= "类型:\r\n"; $fields['infotype'] .= "
    \r\n"; $fields['infotype'] .= "\r\n"; - $fields['infotype'] .= ''."\r\n"; - - if(is_array($ctp->CTags)) - { - foreach($ctp->CTags as $tagid=>$ctag) - { - if(isset($fields[$ctag->GetName()])) { - $ctp->Assign($tagid,$fields[$ctag->GetName()]); + $fields['infotype'] .= '' . "\r\n"; + + if (is_array($ctp->CTags)) { + foreach ($ctp->CTags as $tagid => $ctag) { + if (isset($fields[$ctag->GetName()])) { + $ctp->Assign($tagid, $fields[$ctag->GetName()]); } } $revalue .= $ctp->GetResult(); } - + return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/infolink.lib.php b/include/taglib/infolink.lib.php index e7d3c5e0..740cf1e3 100755 --- a/include/taglib/infolink.lib.php +++ b/include/taglib/infolink.lib.php @@ -1,4 +1,4 @@ ->dede>> 分类信息地区与类型快捷链接 全局标记 @@ -18,127 +18,127 @@ {dede:infolink /} - + >>dede>>*/ - -require_once(DEDEINC.'/enums.func.php'); -require_once(DEDEDATA.'/enums/nativeplace.php'); -require_once(DEDEDATA.'/enums/infotype.php'); -function lib_infolink(&$ctag,&$refObj) +require_once DEDEINC . '/enums.func.php'; +require_once DEDEDATA . '/enums/nativeplace.php'; +require_once DEDEDATA . '/enums/infotype.php'; + +function lib_infolink(&$ctag, &$refObj) { - global $dsql,$nativeplace,$infotype,$hasSetEnumJs,$cfg_cmspath,$cfg_mainsite; - global $em_nativeplaces,$em_infotypes; - + global $dsql, $nativeplace, $infotype, $hasSetEnumJs, $cfg_cmspath, $cfg_mainsite; + global $em_nativeplaces, $em_infotypes; + //属性处理 //$attlist="row|12,titlelen|24"; //FillAttsDefault($ctag->CAttribute->Items,$attlist); //extract($ctag->CAttribute->Items, EXTR_SKIP); - - $cmspath = ( (empty($cfg_cmspath) || !preg_match("#\/$#", $cfg_cmspath)) ? $cfg_cmspath.'/' : $cfg_cmspath ); - $baseurl = preg_replace("#\/$#", '', $cfg_mainsite).$cmspath; - + + $cmspath = ((empty($cfg_cmspath) || !preg_match("#\/$#", $cfg_cmspath)) ? $cfg_cmspath . '/' : $cfg_cmspath); + $baseurl = preg_replace("#\/$#", '', $cfg_mainsite) . $cmspath; + $smalltypes = ''; - if( !empty($refObj->TypeLink->TypeInfos['smalltypes']) ) { + if (!empty($refObj->TypeLink->TypeInfos['smalltypes'])) { $smalltypes = explode(',', $refObj->TypeLink->TypeInfos['smalltypes']); } - - if(empty($refObj->Fields['typeid'])) { + + if (empty($refObj->Fields['typeid'])) { $row = $dsql->GetOne("SELECT id FROM `#@__arctype` WHERE channeltype='-8' And reid = '0' "); $typeid = (is_array($row) ? $row['id'] : 0); - } - else { + } else { $typeid = $refObj->Fields['typeid']; } - + $innerText = trim($ctag->GetInnerText()); - if(empty($innerText)) $innerText = GetSysTemplets("info_link.htm"); + if (empty($innerText)) { + $innerText = GetSysTemplets("info_link.htm"); + } + $ctp = new DedeTagParse(); - $ctp->SetNameSpace('field','[',']'); + $ctp->SetNameSpace('field', '[', ']'); $ctp->LoadSource($innerText); $revalue = $seli = ''; - $channelid = ( empty($refObj->TypeLink->TypeInfos['channeltype']) ? -8 : $refObj->TypeLink->TypeInfos['channeltype'] ); - - $fields = array('nativeplace'=>'','infotype'=>'','typeid'=>$typeid, - 'channelid'=>$channelid,'linkallplace'=>'','linkalltype'=>''); - + $channelid = (empty($refObj->TypeLink->TypeInfos['channeltype']) ? -8 : $refObj->TypeLink->TypeInfos['channeltype']); + + $fields = array('nativeplace' => '', 'infotype' => '', 'typeid' => $typeid, + 'channelid' => $channelid, 'linkallplace' => '', 'linkalltype' => ''); + $fields['nativeplace'] = $fields['infotype'] = ''; - + $fields['linkallplace'] = "不限"; $fields['linkalltype'] = "不限"; - + //地区链接 - if(empty($nativeplace)) - { - foreach($em_nativeplaces as $eid=>$em) - { - if($eid % 500 != 0) continue; + if (empty($nativeplace)) { + foreach ($em_nativeplaces as $eid => $em) { + if ($eid % 500 != 0) { + continue; + } + $fields['nativeplace'] .= " {$em}\r\n"; } - } - else - { - $sontype = ( ($nativeplace % 500 != 0) ? $nativeplace : 0 ); - $toptype = ( ($nativeplace % 500 == 0) ? $nativeplace : ( $nativeplace-($nativeplace%500) ) ); - + } else { + $sontype = (($nativeplace % 500 != 0) ? $nativeplace : 0); + $toptype = (($nativeplace % 500 == 0) ? $nativeplace : ($nativeplace - ($nativeplace % 500))); + $fields['nativeplace'] = " {$em_nativeplaces[$toptype]} >> "; - foreach($em_nativeplaces as $eid=>$em) - { - if($eid < $toptype+1 || $eid > $toptype+499) continue; - if($eid == $nativeplace) { - $fields['nativeplace'] .= " {$em}\r\n"; + foreach ($em_nativeplaces as $eid => $em) { + if ($eid < $toptype + 1 || $eid > $toptype + 499) { + continue; } - else { + + if ($eid == $nativeplace) { + $fields['nativeplace'] .= " {$em}\r\n"; + } else { $fields['nativeplace'] .= " {$em}\r\n"; - } - } + } + } } //小分类链接 - if(empty($infotype) || is_array($smalltypes)) - { - - foreach($em_infotypes as $eid=>$em) - { - if(!is_array($smalltypes) && $eid % 500 != 0) continue; - if(is_array($smalltypes) && !in_array($eid, $smalltypes)) continue; - if($eid == $infotype) - { - $fields['infotype'] .= " {$em}\r\n"; + if (empty($infotype) || is_array($smalltypes)) { + + foreach ($em_infotypes as $eid => $em) { + if (!is_array($smalltypes) && $eid % 500 != 0) { + continue; + } + + if (is_array($smalltypes) && !in_array($eid, $smalltypes)) { + continue; } - else { + + if ($eid == $infotype) { + $fields['infotype'] .= " {$em}\r\n"; + } else { $fields['infotype'] .= " {$em}\r\n"; } } - } - else - { - $sontype = ( ($infotype % 500 != 0) ? $infotype : 0 ); - $toptype = ( ($infotype % 500 == 0) ? $infotype : ( $infotype-($infotype%500) ) ); + } else { + $sontype = (($infotype % 500 != 0) ? $infotype : 0); + $toptype = (($infotype % 500 == 0) ? $infotype : ($infotype - ($infotype % 500))); $fields['infotype'] .= "{$em_infotypes[$toptype]} >> "; - foreach($em_infotypes as $eid=>$em) - { - if($eid < $toptype+1 || $eid > $toptype+499) continue; - if($eid == $infotype) { - $fields['infotype'] .= " {$em}\r\n"; + foreach ($em_infotypes as $eid => $em) { + if ($eid < $toptype + 1 || $eid > $toptype + 499) { + continue; } - else { + + if ($eid == $infotype) { + $fields['infotype'] .= " {$em}\r\n"; + } else { $fields['infotype'] .= " {$em}\r\n"; - } - } + } + } } - - - if(is_array($ctp->CTags)) - { - foreach($ctp->CTags as $tagid=>$ctag) - { - if(isset($fields[$ctag->GetName()])) { - $ctp->Assign($tagid,$fields[$ctag->GetName()]); + + if (is_array($ctp->CTags)) { + foreach ($ctp->CTags as $tagid => $ctag) { + if (isset($fields[$ctag->GetName()])) { + $ctp->Assign($tagid, $fields[$ctag->GetName()]); } } $revalue .= $ctp->GetResult(); } - + return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/json.lib.php b/include/taglib/json.lib.php index dca11045..72ca2e33 100755 --- a/include/taglib/json.lib.php +++ b/include/taglib/json.lib.php @@ -1,55 +1,51 @@ ->dede>> +require_once dirname(__file__) . '/../json.class.php'; +/*>>dede>> JSON数据调用类 全局标记 V57 调用某个远程连接的json数据库 {dede:json url='http://yoursite/json.php' cache=300} - [field:id/]-[field:title/]
    +[field:id/]-[field:title/]
    {/dede:json}
    - url:json数据地址 - cache:缓冲时间 - +url:json数据地址 +cache:缓冲时间 + >>dede>>*/ -function lib_json(&$ctag,&$refObj) +function lib_json(&$ctag, &$refObj) { - global $dsql,$sqlCt,$cfg_soft_lang; - $attlist="url|"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + global $dsql, $sqlCt, $cfg_soft_lang; + $attlist = "url|"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $Innertext = trim($ctag->GetInnerText()); - if($url=='' || $Innertext=='') return ''; + if ($url == '' || $Innertext == '') { + return ''; + } $ctp = new DedeTagParse(); - $ctp->SetNameSpace('field','[',']'); + $ctp->SetNameSpace('field', '[', ']'); $ctp->LoadSource($Innertext); - + $mcache = new MiniCache; $GLOBALS['autoindex'] = 0; $chash = md5($url); - - if(!$row = $mcache->Get($chash)) - { + + if (!$row = $mcache->Get($chash)) { $content = @file_get_contents($url); - + $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE); $row = $json->decode($content); - - if($cfg_soft_lang != 'utf-8') - { + + if ($cfg_soft_lang != 'utf-8') { $row = AutoCharset($row, 'utf-8', 'gb2312'); } $mcache->Save($chash, $row, $cache); @@ -57,144 +53,136 @@ function lib_json(&$ctag,&$refObj) $revalue = ""; - foreach($row as $key => $value) - { + foreach ($row as $key => $value) { $GLOBALS['autoindex']++; - foreach($ctp->CTags as $tagid=>$ctag) - { - if($ctag->GetName()=='array') - { - $ctp->Assign($tagid,$value); - } - else - { - if( !empty($value[$ctag->GetName()])) - { - $ctp->Assign($tagid,$value[$ctag->GetName()]); - } else { - $ctp->Assign($tagid,""); + foreach ($ctp->CTags as $tagid => $ctag) { + if ($ctag->GetName() == 'array') { + $ctp->Assign($tagid, $value); + } else { + if (!empty($value[$ctag->GetName()])) { + $ctp->Assign($tagid, $value[$ctag->GetName()]); + } else { + $ctp->Assign($tagid, ""); } } } $revalue .= $ctp->GetResult(); } - + return $revalue; } // 一个简单的文件缓存类 class MiniCache { - var $_cache_path; - - function __construct() + public $_cache_path; + + public function __construct() { - $this->_cache_path = DEDEDATA.'/cache/json/'; + $this->_cache_path = DEDEDATA . '/cache/json/'; } // 获取缓冲 - function Get($id) - { - if ( ! file_exists($this->_cache_path.$id)) - { - return FALSE; - } - - $data = $this->_ReadFile($this->_cache_path.$id); - $data = unserialize($data); - - if (time() > $data['time'] + $data['ttl']) - { - unlink($this->_cache_path.$id); - return FALSE; - } - - return $data['data']; - } - + public function Get($id) + { + if (!file_exists($this->_cache_path . $id)) { + return false; + } + + $data = $this->_ReadFile($this->_cache_path . $id); + $data = unserialize($data); + + if (time() > $data['time'] + $data['ttl']) { + unlink($this->_cache_path . $id); + return false; + } + + return $data['data']; + } + // 清除缓存 - function Clean() - { - return $this->_DeleteFiles($this->_cache_path); - } - + public function Clean() + { + return $this->_DeleteFiles($this->_cache_path); + } + // 保存缓冲 - function Save($id, $data, $ttl = 60) - { - $contents = array( - 'time' => time(), - 'ttl' => $ttl, - 'data' => $data - ); - - if (PutFile($this->_cache_path.$id, serialize($contents))) - { - @chmod($this->_cache_path.$id, 0777); - return TRUE; - } - - return FALSE; - } - + public function Save($id, $data, $ttl = 60) + { + $contents = array( + 'time' => time(), + 'ttl' => $ttl, + 'data' => $data, + ); + + if (PutFile($this->_cache_path . $id, serialize($contents))) { + @chmod($this->_cache_path . $id, 0777); + return true; + } + + return false; + } + // 删除缓冲 - function Delete($id) - { - return unlink($this->_cache_path.$id); - } - - - function _DeleteFiles($path, $del_dir = FALSE, $level = 0) - { - // Trim the trailing slash - $path = rtrim($path, DIRECTORY_SEPARATOR); - - if ( ! $current_dir = @opendir($path)) - { - return FALSE; - } - - while(FALSE !== ($filename = @readdir($current_dir))) - { - if ($filename != "." and $filename != "..") - { - if (is_dir($path.DIRECTORY_SEPARATOR.$filename)) - { - // Ignore empty folders - if (substr($filename, 0, 1) != '.') - { - delete_files($path.DIRECTORY_SEPARATOR.$filename, $del_dir, $level + 1); - } - } - else - { - unlink($path.DIRECTORY_SEPARATOR.$filename); - } - } - } - @closedir($current_dir); - - if ($del_dir == TRUE AND $level > 0) - { - return @rmdir($path); - } - - return TRUE; - } - - function _ReadFile($file) - { - if ( ! file_exists($file)) return FALSE; - if (function_exists('file_get_contents')) return file_get_contents($file); - if ( ! $fp = @fopen($file, FOPEN_READ)) return FALSE; - - flock($fp, LOCK_SH); - - $data = ''; - if (filesize($file) > 0) $data =& fread($fp, filesize($file)); - - flock($fp, LOCK_UN); - fclose($fp); - - return $data; - } + public function Delete($id) + { + return unlink($this->_cache_path . $id); + } + + public function _DeleteFiles($path, $del_dir = false, $level = 0) + { + // Trim the trailing slash + $path = rtrim($path, DIRECTORY_SEPARATOR); + + if (!$current_dir = @opendir($path)) { + return false; + } + + while (false !== ($filename = @readdir($current_dir))) { + if ($filename != "." and $filename != "..") { + if (is_dir($path . DIRECTORY_SEPARATOR . $filename)) { + // Ignore empty folders + if (substr($filename, 0, 1) != '.') { + delete_files($path . DIRECTORY_SEPARATOR . $filename, $del_dir, $level + 1); + } + } else { + unlink($path . DIRECTORY_SEPARATOR . $filename); + } + } + } + @closedir($current_dir); + + if ($del_dir == true and $level > 0) { + return @rmdir($path); + } + + return true; + } + + public function _ReadFile($file) + { + if (!file_exists($file)) { + return false; + } + + if (function_exists('file_get_contents')) { + return file_get_contents($file); + } + + if (!$fp = @fopen($file, FOPEN_READ)) { + return false; + } + + flock($fp, LOCK_SH); + + $data = ''; + if (filesize($file) > 0) { + $data = &fread($fp, filesize($file)); + } + + flock($fp, LOCK_UN); + fclose($fp); + + return $data; + } } diff --git a/include/taglib/likearticle.lib.php b/include/taglib/likearticle.lib.php index 0fc98a51..65cafd28 100755 --- a/include/taglib/likearticle.lib.php +++ b/include/taglib/likearticle.lib.php @@ -1,4 +1,4 @@ ->dede>> 相关文档 全局标记 @@ -20,110 +20,116 @@ {/dede:likearticle} - col:分多少列显示(默认为单列) - row:返回文档列表总数 - titlelen:标题长度 等同于titlelength - infolen:表示内容简介长度 等同于infolength - mytypeid:手工指定要限定的栏目id,用,分开表示多个 - innertext:单条记录样式(指标签中间的内容) - +col:分多少列显示(默认为单列) +row:返回文档列表总数 +titlelen:标题长度 等同于titlelength +infolen:表示内容简介长度 等同于infolength +mytypeid:手工指定要限定的栏目id,用,分开表示多个 +innertext:单条记录样式(指标签中间的内容) + >>dede>>*/ - -function lib_likearticle(&$ctag,&$refObj) + +function lib_likearticle(&$ctag, &$refObj) { global $dsql; - + //属性处理 - $attlist="row|12,titlelen|28,infolen|150,col|1,tablewidth|100,mytypeid|0,byabs|0,imgwidth|120,imgheight|90"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "row|12,titlelen|28,infolen|150,col|1,tablewidth|100,mytypeid|0,byabs|0,imgwidth|120,imgheight|90"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $revalue = ''; - - if(empty($tablewidth)) $tablewidth = 100; - if(empty($col)) $col = 1; - $colWidth = ceil(100/$col); - $tablewidth = $tablewidth."%"; - $colWidth = $colWidth."%"; - + + if (empty($tablewidth)) { + $tablewidth = 100; + } + + if (empty($col)) { + $col = 1; + } + + $colWidth = ceil(100 / $col); + $tablewidth = $tablewidth . "%"; + $colWidth = $colWidth . "%"; + $ids = array(); $tids = array(); - - if(!empty($refObj->Fields['tags'])) { + + if (!empty($refObj->Fields['tags'])) { $keyword = $refObj->Fields['tags']; + } else { + $keyword = (!empty($refObj->Fields['keywords']) ? $refObj->Fields['keywords'] : ''); } - else { - $keyword = ( !empty($refObj->Fields['keywords']) ? $refObj->Fields['keywords'] : '' ); - } - - $typeid = ( !empty($mytypeid) ? $mytypeid : 0 ); - if(empty($typeid)) - { - if(!empty($refObj->Typelink->TypeInfos['reid'])) { - $typeid = $refObj->Typelink->TypeInfos['reid']; - } - else { - if(!empty($refObj->Fields['typeid'])) $typeid = $refObj->Fields['typeid']; + + $typeid = (!empty($mytypeid) ? $mytypeid : 0); + if (empty($typeid)) { + if (!empty($refObj->Typelink->TypeInfos['reid'])) { + $typeid = $refObj->Typelink->TypeInfos['reid']; + } else { + if (!empty($refObj->Fields['typeid'])) { + $typeid = $refObj->Fields['typeid']; + } + } } - - if( !empty($typeid) && !preg_match('#,#', $typeid) ) { + + if (!empty($typeid) && !preg_match('#,#', $typeid)) { $typeid = GetSonIds($typeid); } - + $limitRow = $row - count($ids); $keyword = ''; - if(!empty($refObj->Fields['keywords'])) - { - $keywords = explode(',' , trim($refObj->Fields['keywords'])); - $keyword = ''; - $n = 1; - foreach($keywords as $k) - { - if($n > 3) break; - - if(trim($k)=='') continue; - else $k = addslashes($k); - - $keyword .= ($keyword=='' ? " CONCAT(arc.keywords,' ',arc.title) LIKE '%$k%' " : " OR CONCAT(arc.keywords,' ',arc.title) LIKE '%$k%' "); - $n++; + if (!empty($refObj->Fields['keywords'])) { + $keywords = explode(',', trim($refObj->Fields['keywords'])); + $keyword = ''; + $n = 1; + foreach ($keywords as $k) { + if ($n > 3) { + break; + } + + if (trim($k) == '') { + continue; + } else { + $k = addslashes($k); } + + $keyword .= ($keyword == '' ? " CONCAT(arc.keywords,' ',arc.title) LIKE '%$k%' " : " OR CONCAT(arc.keywords,' ',arc.title) LIKE '%$k%' "); + $n++; + } } $arcid = (!empty($refObj->Fields['id']) ? $refObj->Fields['aid'] : 0); - if( empty($arcid) || $byabs==0 ) - { - $orderquery = " ORDER BY arc.id desc "; + if (empty($arcid) || $byabs == 0) { + $orderquery = " ORDER BY arc.id desc "; + } else { + $orderquery = " ORDER BY ABS(arc.id - " . $arcid . ") "; } - else { - $orderquery = " ORDER BY ABS(arc.id - ".$arcid.") "; - } - if($keyword != '') - { - if(!empty($typeid)) { - $typeid = " AND arc.typeid IN($typeid) AND arc.id<>$arcid "; - } - $query = "SELECT arc.*,tp.typedir,tp.typename,tp.corank,tp.isdefault,tp.defaultname,tp.namerule, + if ($keyword != '') { + if (!empty($typeid)) { + $typeid = " AND arc.typeid IN($typeid) AND arc.id<>$arcid "; + } + $query = "SELECT arc.*,tp.typedir,tp.typename,tp.corank,tp.isdefault,tp.defaultname,tp.namerule, tp.namerule2,tp.ispart,tp.moresite,tp.siteurl,tp.sitepath FROM `#@__archives` arc LEFT JOIN `#@__arctype` tp ON arc.typeid=tp.id where arc.arcrank>-1 AND ($keyword) $typeid $orderquery limit 0, $row"; - } - else - { - if(!empty($typeid)) { - $typeid = " arc.typeid IN($typeid) AND arc.id<>$arcid "; - } - $query = "SELECT arc.*,tp.typedir,tp.typename,tp.corank,tp.isdefault,tp.defaultname,tp.namerule, + } else { + if (!empty($typeid)) { + $typeid = " arc.typeid IN($typeid) AND arc.id<>$arcid "; + } + $query = "SELECT arc.*,tp.typedir,tp.typename,tp.corank,tp.isdefault,tp.defaultname,tp.namerule, tp.namerule2,tp.ispart,tp.moresite,tp.siteurl,tp.sitepath FROM `#@__archives` arc LEFT JOIN `#@__arctype` tp ON arc.typeid=tp.id WHERE arc.arcrank>-1 AND $typeid $orderquery limit 0, $row"; } - - $innertext = trim( $ctag->GetInnerText() ); - if($innertext=='') $innertext = GetSysTemplets('part_arclist.htm'); + + $innertext = trim($ctag->GetInnerText()); + if ($innertext == '') { + $innertext = GetSysTemplets('part_arclist.htm'); + } $dsql->SetQuery($query); $dsql->Execute('al'); $artlist = ''; - if($col > 1) { + if ($col > 1) { $artlist = "\r\n"; } $dtp2 = new DedeTagParse(); @@ -131,82 +137,100 @@ function lib_likearticle(&$ctag,&$refObj) $dtp2->LoadString($innertext); $GLOBALS['autoindex'] = 0; $line = $row; - for($i=0; $i < $line; $i++) - { - if($col>1) $artlist .= "\r\n"; - for($j=0; $j < $col; $j++) - { - if($col>1) $artlist .= " \r\n"; + } + + for ($j = 0; $j < $col; $j++) { + if ($col > 1) { + $artlist .= " \r\n"; + if ($col > 1) { + $artlist .= " \r\n"; + } + } //Loop Col - if($col>1) $i += $col - 1; - if($col>1) $artlist .= " \r\n"; + if ($col > 1) { + $i += $col - 1; + } + + if ($col > 1) { + $artlist .= " \r\n"; + } + } //loop line - if($col>1) $artlist .= "
    \r\n"; - if($row = $dsql->GetArray("al")) - { + for ($i = 0; $i < $line; $i++) { + if ($col > 1) { + $artlist .= "
    \r\n"; + } + + if ($row = $dsql->GetArray("al")) { $ids[] = $row['id']; //处理一些特殊字段 - $row['info'] = $row['infos'] = cn_substr($row['description'],$infolen); - $row['id'] = $row['id']; + $row['info'] = $row['infos'] = cn_substr($row['description'], $infolen); + $row['id'] = $row['id']; - if($row['corank'] > 0 && $row['arcrank']==0) - { + if ($row['corank'] > 0 && $row['arcrank'] == 0) { $row['arcrank'] = $row['corank']; } - $row['filename'] = $row['arcurl'] = GetFileUrl($row['id'],$row['typeid'],$row['senddate'],$row['title'],$row['ismake'], - $row['arcrank'],$row['namerule'],$row['typedir'],$row['money'],$row['filename'],$row['moresite'],$row['siteurl'],$row['sitepath']); + $row['filename'] = $row['arcurl'] = GetFileUrl($row['id'], $row['typeid'], $row['senddate'], $row['title'], $row['ismake'], + $row['arcrank'], $row['namerule'], $row['typedir'], $row['money'], $row['filename'], $row['moresite'], $row['siteurl'], $row['sitepath']); - $row['typeurl'] = GetTypeUrl($row['typeid'],$row['typedir'],$row['isdefault'],$row['defaultname'],$row['ispart'], - $row['namerule2'],$row['moresite'],$row['siteurl'],$row['sitepath']); + $row['typeurl'] = GetTypeUrl($row['typeid'], $row['typedir'], $row['isdefault'], $row['defaultname'], $row['ispart'], + $row['namerule2'], $row['moresite'], $row['siteurl'], $row['sitepath']); - if($row['litpic'] == '-' || $row['litpic'] == '') - { - $row['litpic'] = $GLOBALS['cfg_cmspath'].'/resources/img/defaultpic.gif'; + if ($row['litpic'] == '-' || $row['litpic'] == '') { + $row['litpic'] = $GLOBALS['cfg_cmspath'] . '/resources/img/defaultpic.gif'; } - if(!preg_match("#^http:\/\/#i", $row['litpic']) && $GLOBALS['cfg_multi_site'] == 'Y') - { - $row['litpic'] = $GLOBALS['cfg_mainsite'].$row['litpic']; + if (!preg_match("#^http:\/\/#i", $row['litpic']) && $GLOBALS['cfg_multi_site'] == 'Y') { + $row['litpic'] = $GLOBALS['cfg_mainsite'] . $row['litpic']; } $row['picname'] = $row['litpic']; $row['stime'] = GetDateMK($row['pubdate']); - $row['typelink'] = "".$row['typename'].""; - $row['image'] = "".preg_replace("#[<]#","",$row['title'])."'>"; - $row['imglink'] = "".$row['image'].""; + $row['typelink'] = "" . $row['typename'] . ""; + $row['image'] = "" . preg_replace("#[<]#", "", $row['title']) . "'>"; + $row['imglink'] = "" . $row['image'] . ""; $row['fulltitle'] = $row['title']; $row['title'] = cn_substr($row['title'], $titlelen); - if($row['color']!='') $row['title'] = "".$row['title'].""; - if(preg_match('#b#', $row['flag'])) $row['title'] = "".$row['title'].""; - $row['textlink'] = "".$row['title'].""; + if ($row['color'] != '') { + $row['title'] = "" . $row['title'] . ""; + } + + if (preg_match('#b#', $row['flag'])) { + $row['title'] = "" . $row['title'] . ""; + } + + $row['textlink'] = "" . $row['title'] . ""; $row['plusurl'] = $row['phpurl'] = $GLOBALS['cfg_phpurl']; $row['memberurl'] = $GLOBALS['cfg_memberurl']; $row['templeturl'] = $GLOBALS['cfg_templeturl']; - - if(is_array($dtp2->CTags)) - { - foreach($dtp2->CTags as $k=>$ctag) - { - if($ctag->GetName()=='array') { - $dtp2->Assign($k,$row); - } - else { - if(isset($row[$ctag->GetName()])) $dtp2->Assign($k,$row[$ctag->GetName()]); - else $dtp2->Assign($k,''); + + if (is_array($dtp2->CTags)) { + foreach ($dtp2->CTags as $k => $ctag) { + if ($ctag->GetName() == 'array') { + $dtp2->Assign($k, $row); + } else { + if (isset($row[$ctag->GetName()])) { + $dtp2->Assign($k, $row[$ctag->GetName()]); + } else { + $dtp2->Assign($k, ''); + } + } } $GLOBALS['autoindex']++; } - $artlist .= $dtp2->GetResult()."\r\n"; + $artlist .= $dtp2->GetResult() . "\r\n"; } //if hasRow - else - { + else { $artlist .= ''; } - if($col>1) $artlist .= "
    \r\n"; + if ($col > 1) { + $artlist .= " \r\n"; + } + $dsql->FreeResult("al"); return $artlist; -} \ No newline at end of file +} diff --git a/include/taglib/likepage.lib.php b/include/taglib/likepage.lib.php index 795340ee..fa0db859 100755 --- a/include/taglib/likepage.lib.php +++ b/include/taglib/likepage.lib.php @@ -8,7 +8,7 @@ * @license http://help.dedecms.com/usersguide/license.html * @link http://www.dedecms.com */ - + /*>>dede>> 单页文档相同标识调用标签 全局标记 @@ -18,15 +18,16 @@ {dede:likepage likeid='' row=''/} - row:调用条数 - likeid:标识名 - +row:调用条数 +likeid:标识名 + >>dede>>*/ - -if(!defined('DEDEINC')) exit('Request Error!'); -require_once(dirname(__FILE__).'/likesgpage.lib.php'); -function lib_likepage(&$ctag,&$refObj) +if (!defined('DEDEINC')) {exit("Request Error!");} + +require_once dirname(__FILE__) . '/likesgpage.lib.php'; + +function lib_likepage(&$ctag, &$refObj) { return lib_likesgpage($ctag, $refObj); } diff --git a/include/taglib/likesgpage.lib.php b/include/taglib/likesgpage.lib.php index ea549004..af04358a 100755 --- a/include/taglib/likesgpage.lib.php +++ b/include/taglib/likesgpage.lib.php @@ -1,4 +1,4 @@ ->dede>> 单页文档调用标签 全局标记 @@ -18,46 +18,47 @@ {dede:likespage row=''/} - row:调用条数 - +row:调用条数 + >>dede>>*/ - -function lib_likesgpage(&$ctag,&$refObj) + +function lib_likesgpage(&$ctag, &$refObj) { global $dsql; //把属性转为变量,如果不想进行此步骤,也可以直接从 $ctag->CAttribute->Items 获得,这样也可以支持中文名 - $attlist="row|8"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "row|8"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $innertext = trim($ctag->GetInnerText()); $aid = (isset($refObj->Fields['aid']) ? $refObj->Fields['aid'] : 0); $revalue = ''; - if($innertext=='') $innertext = GetSysTemplets("part_likesgpage.htm"); + if ($innertext == '') { + $innertext = GetSysTemplets("part_likesgpage.htm"); + } - $likeid = (empty($refObj->Fields['likeid']) ? 'all' : $refObj->Fields['likeid']); + $likeid = (empty($refObj->Fields['likeid']) ? 'all' : $refObj->Fields['likeid']); $dsql->SetQuery("SELECT aid,title,filename FROM `#@__sgpage` WHERE likeid LIKE '$likeid' LIMIT 0,$row"); $dsql->Execute(); $ctp = new DedeTagParse(); - $ctp->SetNameSpace('field','[',']'); + $ctp->SetNameSpace('field', '[', ']'); $ctp->LoadSource($innertext); - while($row = $dsql->GetArray()) - { - if($aid != $row['aid']) - { - $row['url'] = $GLOBALS['cfg_cmsurl'].'/'.$row['filename']; - foreach($ctp->CTags as $tagid=>$ctag) { - if(!empty($row[$ctag->GetName()])) $ctp->Assign($tagid,$row[$ctag->GetName()]); + while ($row = $dsql->GetArray()) { + if ($aid != $row['aid']) { + $row['url'] = $GLOBALS['cfg_cmsurl'] . '/' . $row['filename']; + foreach ($ctp->CTags as $tagid => $ctag) { + if (!empty($row[$ctag->GetName()])) { + $ctp->Assign($tagid, $row[$ctag->GetName()]); + } + } $revalue .= $ctp->GetResult(); - } - else - { - $revalue .= '
    '.$row['title'].'
    '; + } else { + $revalue .= '
    ' . $row['title'] . '
    '; } } return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/loop.lib.php b/include/taglib/loop.lib.php index c1ba4389..d843a6f4 100755 --- a/include/taglib/loop.lib.php +++ b/include/taglib/loop.lib.php @@ -1,8 +1,4 @@ ->dede>> 万能循环 全局标记 @@ -24,51 +20,62 @@ {/dede:loop} - table:查询表名 - sort:用于排序的字段 - row:返回结果的条数 - if:查询的条件 - +table:查询表名 +sort:用于排序的字段 +row:返回结果的条数 +if:查询的条件 + >>dede>>*/ - -require_once(DEDEINC.'/dedevote.class.php'); -function lib_loop(&$ctag,&$refObj) + +require_once DEDEINC . '/dedevote.class.php'; +function lib_loop(&$ctag, &$refObj) { global $dsql; - $attlist="table|,tablename|,row|8,sort|,if|,ifcase|,orderway|desc"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "table|,tablename|,row|8,sort|,if|,ifcase|,orderway|desc"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $innertext = trim($ctag->GetInnertext()); $revalue = ''; - if(!empty($table)) $tablename = $table; + if (!empty($table)) { + $tablename = $table; + } + + if ($tablename == '' || $innertext == '') { + return ''; + } - if($tablename==''||$innertext=='') return ''; - if($if!='') $ifcase = $if; + if ($if != '') { + $ifcase = $if; + } + + if ($sort != '') { + $sort = " ORDER BY $sort $orderway "; + } + + if ($ifcase != '') { + $ifcase = " WHERE $ifcase "; + } - if($sort!='') $sort = " ORDER BY $sort $orderway "; - if($ifcase!='') $ifcase=" WHERE $ifcase "; $dsql->SetQuery("SELECT * FROM $tablename $ifcase $sort LIMIT 0,$row"); $dsql->Execute(); $ctp = new DedeTagParse(); - $ctp->SetNameSpace("field","[","]"); + $ctp->SetNameSpace("field", "[", "]"); $ctp->LoadSource($innertext); $GLOBALS['autoindex'] = 0; - while($row = $dsql->GetArray()) - { + while ($row = $dsql->GetArray()) { $GLOBALS['autoindex']++; - foreach($ctp->CTags as $tagid=>$ctag) - { - if($ctag->GetName()=='array') - { - $ctp->Assign($tagid, $row); - } - else - { - if( !empty($row[$ctag->GetName()])) $ctp->Assign($tagid,$row[$ctag->GetName()]); + foreach ($ctp->CTags as $tagid => $ctag) { + if ($ctag->GetName() == 'array') { + $ctp->Assign($tagid, $row); + } else { + if (!empty($row[$ctag->GetName()])) { + $ctp->Assign($tagid, $row[$ctag->GetName()]); } + + } } $revalue .= $ctp->GetResult(); } return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/mda.lib.php b/include/taglib/mda.lib.php index 8efc94bf..32a89721 100755 --- a/include/taglib/mda.lib.php +++ b/include/taglib/mda.lib.php @@ -1,67 +1,67 @@ -CAttribute->Items,$attlist); + $attlist = "uuid|,name|"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - if ( empty($uuid) AND empty($name) ) return '填写正确的uuid 或 name'; - - $reval=""; - + if (empty($uuid) and empty($name)) { + return '填写正确的uuid 或 name'; + } + + $reval = ""; + //if( !$dsql->IsTable("#@__plus_mda_setting") ) return '没安装德得广告模块'; - + $email = mda_get_setting('email'); $channel_uuid = mda_get_setting('channel_uuid'); - + $channel_secret = mda_get_setting('channel_secret'); - + //if(empty($channel_uuid)) return '尚未绑定德得广告账号,请注册并到系统后台绑定'; - + $prefix = 'mda'; - $key = 'code'.md5($uuid.$name); + $key = 'code' . md5($uuid . $name); $row = GetCache($prefix, $key); - if(!is_array($row)) - { + if (!is_array($row)) { $ts = time(); - $paramsArr=array( - 'channel_uuid'=>$channel_uuid, - 'channel_secret'=>$channel_secret, - 'ts'=>$ts, - 'crc'=>md5($channel_uuid.$channel_secret.$ts), + $paramsArr = array( + 'channel_uuid' => $channel_uuid, + 'channel_secret' => $channel_secret, + 'ts' => $ts, + 'crc' => md5($channel_uuid . $channel_secret . $ts), ); - if ( !empty($uuid) ) - { + if (!empty($uuid)) { $paramsArr['place_uuid'] = $uuid; } else { $paramsArr['tag_name'] = urlencode($name); } - $place = json_decode(mda_http_send(MDA_API_GET_PLACE,0,$paramsArr),TRUE); - - if (!isset($place['data']['place_code']) ) - { + $place = json_decode(mda_http_send(MDA_API_GET_PLACE, 0, $paramsArr), true); + + if (!isset($place['data']['place_code'])) { return ''; } - + $row['reval'] = htmlspecialchars($place['data']['place_code']); - SetCache($prefix, $key, $row, 60*60*12); + SetCache($prefix, $key, $row, 60 * 60 * 12); + } + + if ($cfg_soft_lang != 'utf-8') { + $row = AutoCharset($row, 'utf-8', 'gb2312'); } - if($cfg_soft_lang != 'utf-8') $row = AutoCharset($row, 'utf-8', 'gb2312'); - $reval .= htmlspecialchars_decode($row['reval']); - + return $reval; } - diff --git a/include/taglib/memberinfos.lib.php b/include/taglib/memberinfos.lib.php index c36c53ed..a717d276 100755 --- a/include/taglib/memberinfos.lib.php +++ b/include/taglib/memberinfos.lib.php @@ -1,8 +1,4 @@ ->dede>> 用户信息 全局标记 @@ -22,53 +18,57 @@ {dede:memberinfos mid = '' /} - mid:用户ID - +mid:用户ID + >>dede>>*/ - -function lib_memberinfos(&$ctag,&$refObj) + +function lib_memberinfos(&$ctag, &$refObj) { - global $dsql,$sqlCt; - $attlist="mid|0"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + global $dsql, $sqlCt; + $attlist = "mid|0"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - - if(empty($mid)) - { - if(!empty($refObj->Fields['mid'])) $mid = $refObj->Fields['mid']; - else $mid = 1; - } - else - { - $mid = intval($mid); + + if (empty($mid)) { + if (!empty($refObj->Fields['mid'])) { + $mid = $refObj->Fields['mid']; + } else { + $mid = 1; + } + + } else { + $mid = intval($mid); } $revalue = ''; $innerText = trim($ctag->GetInnerText()); - if(empty($innerText)) $innerText = GetSysTemplets('memberinfos.htm'); + if (empty($innerText)) { + $innerText = GetSysTemplets('memberinfos.htm'); + } $sql = "SELECT mb.*,ms.spacename,ms.sign,ar.membername as rankname FROM `#@__member` mb - LEFT JOIN `#@__member_space` ms ON ms.mid = mb.mid + LEFT JOIN `#@__member_space` ms ON ms.mid = mb.mid LEFT JOIN `#@__arcrank` ar ON ar.rank = mb.rank WHERE mb.mid='{$mid}' LIMIT 0,1 "; $ctp = new DedeTagParse(); - $ctp->SetNameSpace('field','[',']'); + $ctp->SetNameSpace('field', '[', ']'); $ctp->LoadSource($innerText); - $dsql->Execute('mb',$sql); - while($row = $dsql->GetArray('mb')) - { - if($row['matt']==10) return ''; - $row['spaceurl'] = $GLOBALS['cfg_basehost'].'/member/index.php?uid='.$row['userid']; - if(empty($row['face'])) { - $row['face']=($row['sex']=='女')? $GLOBALS['cfg_memberurl'].'/templets/images/dfgirl.png' : $GLOBALS['cfg_memberurl'].'/templets/images/dfboy.png'; + $dsql->Execute('mb', $sql); + while ($row = $dsql->GetArray('mb')) { + if ($row['matt'] == 10) { + return ''; } - foreach($ctp->CTags as $tagid=>$ctag) - { - if(isset($row[$ctag->GetName()])){ $ctp->Assign($tagid,$row[$ctag->GetName()]); } + + $row['spaceurl'] = $GLOBALS['cfg_basehost'] . '/member/index.php?uid=' . $row['userid']; + if (empty($row['face'])) { + $row['face'] = ($row['sex'] == '女') ? $GLOBALS['cfg_memberurl'] . '/templets/images/dfgirl.png' : $GLOBALS['cfg_memberurl'] . '/templets/images/dfboy.png'; + } + foreach ($ctp->CTags as $tagid => $ctag) { + if (isset($row[$ctag->GetName()])) {$ctp->Assign($tagid, $row[$ctag->GetName()]);} } $revalue .= $ctp->GetResult(); } return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/memberlist.lib.php b/include/taglib/memberlist.lib.php index 5d787302..0656a21b 100755 --- a/include/taglib/memberlist.lib.php +++ b/include/taglib/memberlist.lib.php @@ -1,8 +1,4 @@ ->dede>> 会员信息列表 全局标记 @@ -25,48 +21,51 @@ {/dede:memberlist} - row:调用数目 - iscommend:是否为推荐会员 - orderby:按登陆时间排序 money 按金钱排序 scores 按积分排序 - +row:调用数目 +iscommend:是否为推荐会员 +orderby:按登陆时间排序 money 按金钱排序 scores 按积分排序 + >>dede>>*/ - + //orderby = logintime(login new) or mid(register new) function lib_memberlist(&$ctag, &$refObj) { - global $dsql,$sqlCt; - $attlist="row|6,iscommend|0,orderby|logintime,signlen|50"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + global $dsql, $sqlCt; + $attlist = "row|6,iscommend|0,orderby|logintime,signlen|50"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $revalue = ''; $innerText = trim($ctag->GetInnerText()); - if(empty($innerText)) $innerText = GetSysTemplets('memberlist.htm'); + if (empty($innerText)) { + $innerText = GetSysTemplets('memberlist.htm'); + } $wheresql = ' WHERE mb.spacesta>-1 AND mb.matt<10 '; - if($iscommend > 0) $wheresql .= " AND mb.matt='$iscommend' "; + if ($iscommend > 0) { + $wheresql .= " AND mb.matt='$iscommend' "; + } $sql = "SELECT mb.*,ms.spacename,ms.sign FROM `#@__member` mb LEFT JOIN `#@__member_space` ms ON ms.mid = mb.mid $wheresql order by mb.{$orderby} DESC LIMIT 0,$row "; - + $ctp = new DedeTagParse(); - $ctp->SetNameSpace('field','[',']'); + $ctp->SetNameSpace('field', '[', ']'); $ctp->LoadSource($innerText); - $dsql->Execute('mb',$sql); - while($row = $dsql->GetArray('mb')) - { - $row['spaceurl'] = $GLOBALS['cfg_basehost'].'/member/index.php?uid='.$row['userid']; - if(empty($row['face'])){ - $row['face']=($row['sex']=='女')? $GLOBALS['cfg_memberurl'].'/templets/images/dfgirl.png' : $GLOBALS['cfg_memberurl'].'/templets/images/dfboy.png'; + $dsql->Execute('mb', $sql); + while ($row = $dsql->GetArray('mb')) { + $row['spaceurl'] = $GLOBALS['cfg_basehost'] . '/member/index.php?uid=' . $row['userid']; + if (empty($row['face'])) { + $row['face'] = ($row['sex'] == '女') ? $GLOBALS['cfg_memberurl'] . '/templets/images/dfgirl.png' : $GLOBALS['cfg_memberurl'] . '/templets/images/dfboy.png'; } - foreach($ctp->CTags as $tagid=>$ctag){ - if(isset($row[$ctag->GetName()])){ $ctp->Assign($tagid,$row[$ctag->GetName()]); } + foreach ($ctp->CTags as $tagid => $ctag) { + if (isset($row[$ctag->GetName()])) {$ctp->Assign($tagid, $row[$ctag->GetName()]);} } $revalue .= $ctp->GetResult(); } - + return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/myad.lib.php b/include/taglib/myad.lib.php index 550e2b01..3661a64b 100755 --- a/include/taglib/myad.lib.php +++ b/include/taglib/myad.lib.php @@ -1,4 +1,4 @@ ->dede>> 广告标签 全局标记 @@ -18,20 +18,20 @@ {dede:myad name=''/} - typeid:投放范围,0为全站 - name:广告标识 - +typeid:投放范围,0为全站 +name:广告标识 + >>dede>>*/ - -require_once(DEDEINC.'/taglib/mytag.lib.php'); + +require_once DEDEINC . '/taglib/mytag.lib.php'; function lib_myad(&$ctag, &$refObj) { $attlist = "typeid|0,name|"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $body = lib_GetMyTagT($refObj, $typeid, $name, '#@__myad'); - + return $body; -} \ No newline at end of file +} diff --git a/include/taglib/mynews.lib.php b/include/taglib/mynews.lib.php index fc365d4e..cedf2850 100755 --- a/include/taglib/mynews.lib.php +++ b/include/taglib/mynews.lib.php @@ -8,7 +8,7 @@ * @license http://help.dedecms.com/usersguide/license.html * @link http://www.dedecms.com */ - + /*>>dede>> 站内新闻 全局标记 @@ -18,38 +18,48 @@ {dede:mynews row='' titlelen=''/} - row:调用站内新闻数 - titlelen:新闻标题长度 - +row:调用站内新闻数 +titlelen:新闻标题长度 + >>dede>>*/ - -function lib_mynews(&$ctag,&$refObj) + +function lib_mynews(&$ctag, &$refObj) { - global $dsql,$envs; + global $dsql, $envs; //属性处理 - $attlist="row|1,titlelen|24"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + $attlist = "row|1,titlelen|24"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $innertext = trim($ctag->GetInnerText()); - if(empty($row)) $row=1; - if(empty($titlelen)) $titlelen=30; - if(empty($innertext)) $innertext = GetSysTemplets('mynews.htm'); + if (empty($row)) { + $row = 1; + } + + if (empty($titlelen)) { + $titlelen = 30; + } + + if (empty($innertext)) { + $innertext = GetSysTemplets('mynews.htm'); + } $idsql = ''; - if($envs['typeid'] > 0) $idsql = " WHERE typeid='".GetTopid($this->TypeID)."' "; + if ($envs['typeid'] > 0) { + $idsql = " WHERE typeid='" . GetTopid($this->TypeID) . "' "; + } + $dsql->SetQuery("SELECT * FROM #@__mynews $idsql ORDER BY senddate DESC LIMIT 0,$row"); $dsql->Execute(); $ctp = new DedeTagParse(); - $ctp->SetNameSpace('field','[',']'); + $ctp->SetNameSpace('field', '[', ']'); $ctp->LoadSource($innertext); $revalue = ''; - while($row = $dsql->GetArray()) - { - foreach($ctp->CTags as $tagid=>$ctag){ - @$ctp->Assign($tagid,$row[$ctag->GetName()]); + while ($row = $dsql->GetArray()) { + foreach ($ctp->CTags as $tagid => $ctag) { + @$ctp->Assign($tagid, $row[$ctag->GetName()]); } $revalue .= $ctp->GetResult(); } return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/mytag.lib.php b/include/taglib/mytag.lib.php index 84c13c49..5332a425 100755 --- a/include/taglib/mytag.lib.php +++ b/include/taglib/mytag.lib.php @@ -1,4 +1,4 @@ ->dede>> 自定义宏标记 全局标记 @@ -18,54 +18,65 @@ {dede:mytag typeid='0' name=''/} - name:标记名称,该项是必须的属性,以下 2、3是可选属性 - ismake:默认是 no 表示设定的纯HTML代码, yes 表示含板块标记的代码 - typeid:表示所属栏目的ID,默认为 0 ,表示所有栏目通用的显示内容,在列表和文档模板中,typeid默认是这个列表或文档本身的栏目ID - +name:标记名称,该项是必须的属性,以下 2、3是可选属性 +ismake:默认是 no 表示设定的纯HTML代码, yes 表示含板块标记的代码 +typeid:表示所属栏目的ID,默认为 0 ,表示所有栏目通用的显示内容,在列表和文档模板中,typeid默认是这个列表或文档本身的栏目ID + >>dede>>*/ - + function lib_mytag(&$ctag, &$refObj) { $attlist = "typeid|0,name|,ismake|no"; - FillAttsDefault($ctag->CAttribute->Items,$attlist); + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - if(trim($ismake)=='') $ismake = 'no'; + if (trim($ismake) == '') { + $ismake = 'no'; + } + $body = lib_GetMyTagT($refObj, $typeid, $name, '#@__mytag'); //编译 - if($ismake=='yes') - { - require_once(DEDEINC.'/arc.partview.class.php'); + if ($ismake == 'yes') { + require_once DEDEINC . '/arc.partview.class.php'; $pvCopy = new PartView($typeid); - $pvCopy->SetTemplet($body,"string"); + $pvCopy->SetTemplet($body, "string"); $body = $pvCopy->GetResult(); } return $body; } -function lib_GetMyTagT(&$refObj, $typeid,$tagname,$tablename) +function lib_GetMyTagT(&$refObj, $typeid, $tagname, $tablename) { global $dsql; - if($tagname=='') return ''; - if(trim($typeid)=='') $typeid=0; - if( !empty($refObj->Fields['typeid']) && $typeid==0) $typeid = $refObj->Fields['typeid']; - + if ($tagname == '') { + return ''; + } + + if (trim($typeid) == '') { + $typeid = 0; + } + + if (!empty($refObj->Fields['typeid']) && $typeid == 0) { + $typeid = $refObj->Fields['typeid']; + } + $typesql = $row = ''; - if($typeid > 0) $typesql = " And typeid IN(0,".GetTopids($typeid).") "; - + if ($typeid > 0) { + $typesql = " And typeid IN(0," . GetTopids($typeid) . ") "; + } + $row = $dsql->GetOne(" SELECT * FROM $tablename WHERE tagname LIKE '$tagname' $typesql ORDER BY typeid DESC "); - if(!is_array($row)) return ''; + if (!is_array($row)) { + return ''; + } $nowtime = time(); - if($row['timeset']==1 - && ($nowtime<$row['starttime'] || $nowtime>$row['endtime']) ) - { + if ($row['timeset'] == 1 + && ($nowtime < $row['starttime'] || $nowtime > $row['endtime'])) { $body = $row['expbody']; - } - else - { + } else { $body = $row['normbody']; } - + return $body; -} \ No newline at end of file +} diff --git a/include/taglib/php.lib.php b/include/taglib/php.lib.php index a9533ae4..0097ff2b 100755 --- a/include/taglib/php.lib.php +++ b/include/taglib/php.lib.php @@ -1,8 +1,6 @@ ->dede>> + +/*>>dede>> PHP代码标签 全局标记 V55,V56,V57 @@ -23,20 +21,22 @@ {/dede:php} - + >>dede>>*/ - + function lib_php(&$ctag, &$refObj) { global $dsql; global $db; $phpcode = trim($ctag->GetInnerText()); - if ($phpcode == '') + if ($phpcode == '') { return ''; + } + ob_start(); extract($GLOBALS, EXTR_SKIP); @eval($phpcode); $revalue = ob_get_contents(); ob_clean(); return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/productimagelist.lib.php b/include/taglib/productimagelist.lib.php index c1512e61..6a00997f 100755 --- a/include/taglib/productimagelist.lib.php +++ b/include/taglib/productimagelist.lib.php @@ -1,7 +1,6 @@ -CAttribute->Items,$attlist); + global $dsql, $sqlCt; + $attlist = "desclen|80"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); - if(!isset($refObj->addTableRow['imgurls'])) return ; - + if (!isset($refObj->addTableRow['imgurls'])) { + return; + } + $revalue = ''; $innerText = trim($ctag->GetInnerText()); - if(empty($innerText)) $innerText = GetSysTemplets('productimagelist.htm'); - + if (empty($innerText)) { + $innerText = GetSysTemplets('productimagelist.htm'); + } + $dtp = new DedeTagParse(); $dtp->LoadSource($refObj->addTableRow['imgurls']); - + $images = array(); - if(is_array($dtp->CTags)) - { - foreach($dtp->CTags as $ctag) - { - if($ctag->GetName()=="img") - { + if (is_array($dtp->CTags)) { + foreach ($dtp->CTags as $ctag) { + if ($ctag->GetName() == "img") { $row = array(); $row['imgsrc'] = trim($ctag->GetInnerText()); $row['text'] = $ctag->GetAtt('text'); @@ -44,16 +44,14 @@ function lib_productimagelist(&$ctag, &$refObj) $revalue = ''; $ctp = new DedeTagParse(); - $ctp->SetNameSpace('field','[',']'); + $ctp->SetNameSpace('field', '[', ']'); $ctp->LoadSource($innerText); - foreach($images as $row) - { - foreach($ctp->CTags as $tagid=>$ctag) - { - if(isset($row[$ctag->GetName()])){ $ctp->Assign($tagid,$row[$ctag->GetName()]); } + foreach ($images as $row) { + foreach ($ctp->CTags as $tagid => $ctag) { + if (isset($row[$ctag->GetName()])) {$ctp->Assign($tagid, $row[$ctag->GetName()]);} } $revalue .= $ctp->GetResult(); } return $revalue; -} \ No newline at end of file +} diff --git a/include/taglib/qrcode.lib.php b/include/taglib/qrcode.lib.php index 03f2e931..b8dbdc81 100755 --- a/include/taglib/qrcode.lib.php +++ b/include/taglib/qrcode.lib.php @@ -1,37 +1,33 @@ -CAttribute->Items,$attlist); + $attlist = "type|,id|"; + FillAttsDefault($ctag->CAttribute->Items, $attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); //var_dump($refObj->Fields['id']); - if ( empty($type) AND empty($id) ) - { - if ( get_class ($refObj) == 'Archives' ) - { + if (empty($type) and empty($id)) { + if (get_class($refObj) == 'Archives') { $type = 'arc'; $id = $refObj->Fields['id']; - } elseif ( get_class($refObj)=='ListView' OR get_class($refObj)=='SgListView') - { + } elseif (get_class($refObj) == 'ListView' or get_class($refObj) == 'SgListView') { $type = 'list'; $id = $refObj->Fields['id']; - } elseif ( get_class($refObj) =='PartView' AND !empty($refObj->Fields['id']) ) - { + } elseif (get_class($refObj) == 'PartView' and !empty($refObj->Fields['id'])) { $type = 'list'; $id = $refObj->Fields['id']; - } elseif ( get_class($refObj) =='PartView' AND empty($refObj->Fields['id']) ) - { + } elseif (get_class($refObj) == 'PartView' and empty($refObj->Fields['id'])) { $type = 'index'; $id = 0; } } - - $reval=<<织梦二维码生成器 "); + $conn = mysql_connect($dbhost, $dbuser, $dbpwd) or die(""); - mysql_query("CREATE DATABASE IF NOT EXISTS `".$dbname."`;",$conn); + mysql_query("CREATE DATABASE IF NOT EXISTS `" . $dbname . "`;", $conn); mysql_select_db($dbname, $conn) or die(""); //获得数据库版本信息 - $rs = mysql_query("SELECT VERSION();",$conn); + $rs = mysql_query("SELECT VERSION();", $conn); $row = mysql_fetch_array($rs); - $mysqlVersions = explode('.',trim($row[0])); - $mysqlVersion = $mysqlVersions[0].".".$mysqlVersions[1]; + $mysqlVersions = explode('.', trim($row[0])); + $mysqlVersion = $mysqlVersions[0] . "." . $mysqlVersions[1]; - mysql_query("SET NAMES '$dblang',character_set_client=binary,sql_mode='';",$conn); + mysql_query("SET NAMES '$dblang',character_set_client=binary,sql_mode='';", $conn); } - - $fp = fopen(dirname(__FILE__)."/common.inc.php","r"); - $configStr1 = fread($fp,filesize(dirname(__FILE__)."/common.inc.php")); + $fp = fopen(dirname(__FILE__) . "/common.inc.php", "r"); + $configStr1 = fread($fp, filesize(dirname(__FILE__) . "/common.inc.php")); fclose($fp); - $fp = fopen(dirname(__FILE__)."/config.cache.inc.php","r"); - $configStr2 = fread($fp,filesize(dirname(__FILE__)."/config.cache.inc.php")); + $fp = fopen(dirname(__FILE__) . "/config.cache.inc.php", "r"); + $configStr2 = fread($fp, filesize(dirname(__FILE__) . "/config.cache.inc.php")); fclose($fp); //common.inc.php - $configStr1 = str_replace("~dbtype~",$dbtype,$configStr1); - $configStr1 = str_replace("~dbhost~",$dbhost,$configStr1); - $configStr1 = str_replace("~dbname~",$dbname,$configStr1); - $configStr1 = str_replace("~dbuser~",$dbuser,$configStr1); - $configStr1 = str_replace("~dbpwd~",$dbpwd,$configStr1); - $configStr1 = str_replace("~dbprefix~",$dbprefix,$configStr1); - $configStr1 = str_replace("~dblang~",$dblang,$configStr1); - - @chmod(DEDEDATA,0777); - $fp = fopen(DEDEDATA."/common.inc.php","w") or die(""); - fwrite($fp,$configStr1); + $configStr1 = str_replace("~dbtype~", $dbtype, $configStr1); + $configStr1 = str_replace("~dbhost~", $dbhost, $configStr1); + $configStr1 = str_replace("~dbname~", $dbname, $configStr1); + $configStr1 = str_replace("~dbuser~", $dbuser, $configStr1); + $configStr1 = str_replace("~dbpwd~", $dbpwd, $configStr1); + $configStr1 = str_replace("~dbprefix~", $dbprefix, $configStr1); + $configStr1 = str_replace("~dblang~", $dblang, $configStr1); + + @chmod(DEDEDATA, 0777); + $fp = fopen(DEDEDATA . "/common.inc.php", "w") or die(""); + fwrite($fp, $configStr1); fclose($fp); //config.cache.inc.php $cmspath = trim(preg_replace("#\/{1,}#", '/', $cmspath)); - if($cmspath!='' && !preg_match("#^\/#", $cmspath)) $cmspath = '/'.$cmspath; + if ($cmspath != '' && !preg_match("#^\/#", $cmspath)) { + $cmspath = '/' . $cmspath; + } - if($cmspath=='') $indexUrl = '/'; - else $indexUrl = $cmspath; + if ($cmspath == '') { + $indexUrl = '/'; + } else { + $indexUrl = $cmspath; + } - $configStr2 = str_replace("~baseurl~",$baseurl,$configStr2); - $configStr2 = str_replace("~basepath~",$cmspath,$configStr2); - $configStr2 = str_replace("~indexurl~",$indexUrl,$configStr2); - $configStr2 = str_replace("~cookieEncode~",$cookieencode,$configStr2); - $configStr2 = str_replace("~webname~",$webname,$configStr2); - $configStr2 = str_replace("~adminmail~",$adminmail,$configStr2); + $configStr2 = str_replace("~baseurl~", $baseurl, $configStr2); + $configStr2 = str_replace("~basepath~", $cmspath, $configStr2); + $configStr2 = str_replace("~indexurl~", $indexUrl, $configStr2); + $configStr2 = str_replace("~cookieEncode~", $cookieencode, $configStr2); + $configStr2 = str_replace("~webname~", $webname, $configStr2); + $configStr2 = str_replace("~adminmail~", $adminmail, $configStr2); - $fp = fopen(DEDEDATA.'/config.cache.inc.php','w'); - fwrite($fp,$configStr2); + $fp = fopen(DEDEDATA . '/config.cache.inc.php', 'w'); + fwrite($fp, $configStr2); fclose($fp); - $fp = fopen(DEDEDATA.'/config.cache.bak.php','w'); - fwrite($fp,$configStr2); + $fp = fopen(DEDEDATA . '/config.cache.bak.php', 'w'); + fwrite($fp, $configStr2); fclose($fp); - if($mysqlVersion >= 4.1) - { - $sql4tmp = "ENGINE=MyISAM DEFAULT CHARSET=".$dblang; + if ($mysqlVersion >= 4.1) { + $sql4tmp = "ENGINE=MyISAM DEFAULT CHARSET=" . $dblang; } //创建数据表 $query = ''; - $fp = fopen(dirname(__FILE__).'/sql-dftables.txt','r'); - while(!feof($fp)) - { - $line = rtrim(fgets($fp,1024)); - if(preg_match("#;$#", $line)) - { - $query .= $line."\n"; - $query = str_replace('#@__',$dbprefix,$query); - if ( $dbtype == 'sqlite' ) - { - $query = preg_replace('/character set (.*?) /i','',$query); - $query = str_replace('unsigned','',$query); - $query = str_replace('TYPE=MyISAM','',$query); - - $query = preg_replace ('/TINYINT\(([\d]+)\)/i','INTEGER',$query); - $query = preg_replace ('/mediumint\(([\d]+)\)/i','INTEGER',$query); - $query = preg_replace ('/smallint\(([\d]+)\)/i','INTEGER',$query); - $query = preg_replace('/int\(([\d]+)\)/i','INTEGER',$query); - $query = preg_replace('/auto_increment/i','PRIMARY KEY AUTOINCREMENT',$query); - $query = preg_replace('/, KEY(.*?)MyISAM;/','',$query); - $query = preg_replace('/, KEY(.*?);/',');',$query); - $query = preg_replace('/, UNIQUE KEY(.*?);/',');',$query); - $query = preg_replace('/set\(([^\)]*?)\)/','varchar',$query); - $query = preg_replace('/enum\(([^\)]*?)\)/','varchar',$query); - if ( preg_match("/PRIMARY KEY AUTOINCREMENT/",$query) ) - { - $query = preg_replace('/,([\t\s ]+)PRIMARY KEY \(`([0-9a-zA-Z]+)`\)/i','',$query); - $query = str_replace(', PRIMARY KEY (`id`)','',$query); + $fp = fopen(dirname(__FILE__) . '/sql-dftables.txt', 'r'); + while (!feof($fp)) { + $line = rtrim(fgets($fp, 1024)); + if (preg_match("#;$#", $line)) { + $query .= $line . "\n"; + $query = str_replace('#@__', $dbprefix, $query); + if ($dbtype == 'sqlite') { + $query = preg_replace('/character set (.*?) /i', '', $query); + $query = str_replace('unsigned', '', $query); + $query = str_replace('TYPE=MyISAM', '', $query); + + $query = preg_replace('/TINYINT\(([\d]+)\)/i', 'INTEGER', $query); + $query = preg_replace('/mediumint\(([\d]+)\)/i', 'INTEGER', $query); + $query = preg_replace('/smallint\(([\d]+)\)/i', 'INTEGER', $query); + $query = preg_replace('/int\(([\d]+)\)/i', 'INTEGER', $query); + $query = preg_replace('/auto_increment/i', 'PRIMARY KEY AUTOINCREMENT', $query); + $query = preg_replace('/, KEY(.*?)MyISAM;/', '', $query); + $query = preg_replace('/, KEY(.*?);/', ');', $query); + $query = preg_replace('/, UNIQUE KEY(.*?);/', ');', $query); + $query = preg_replace('/set\(([^\)]*?)\)/', 'varchar', $query); + $query = preg_replace('/enum\(([^\)]*?)\)/', 'varchar', $query); + if (preg_match("/PRIMARY KEY AUTOINCREMENT/", $query)) { + $query = preg_replace('/,([\t\s ]+)PRIMARY KEY \(`([0-9a-zA-Z]+)`\)/i', '', $query); + $query = str_replace(', PRIMARY KEY (`id`)', '', $query); } $db->exec($query); } else { - if($mysqlVersion < 4.1) - { - $rs = mysql_query($query,$conn); + if ($mysqlVersion < 4.1) { + $rs = mysql_query($query, $conn); } else { - if(preg_match('#CREATE#i', $query)) - { - $rs = mysql_query(preg_replace("#TYPE=MyISAM#i",$sql4tmp,$query),$conn); - } - else - { - $rs = mysql_query($query,$conn); + if (preg_match('#CREATE#i', $query)) { + $rs = mysql_query(preg_replace("#TYPE=MyISAM#i", $sql4tmp, $query), $conn); + } else { + $rs = mysql_query($query, $conn); } } } - - $query=''; - } else if(!preg_match("#^(\/\/|--)#", $line)) - { + + $query = ''; + } else if (!preg_match("#^(\/\/|--)#", $line)) { $query .= $line; } } @@ -257,28 +251,28 @@ function _4_Setup() //导入默认数据 $query = ''; - $fp = fopen(dirname(__FILE__).'/sql-dfdata.txt','r'); - while(!feof($fp)) - { + $fp = fopen(dirname(__FILE__) . '/sql-dfdata.txt', 'r'); + while (!feof($fp)) { $line = rtrim(fgets($fp, 1024)); - if(preg_match("#;$#", $line)) - { - if ( $dbtype == 'sqlite' ) - { + if (preg_match("#;$#", $line)) { + if ($dbtype == 'sqlite') { $query .= $line; - $query = str_replace('#@__',$dbprefix,$query); - $query = str_replace("\'","\"",$query); + $query = str_replace('#@__', $dbprefix, $query); + $query = str_replace("\'", "\"", $query); $db->exec($query); } else { $query .= $line; - $query = str_replace('#@__',$dbprefix,$query); - if($mysqlVersion < 4.1) $rs = mysql_query($query,$conn); - else $rs = mysql_query(str_replace('#~lang~#',$dblang,$query),$conn); + $query = str_replace('#@__', $dbprefix, $query); + if ($mysqlVersion < 4.1) { + $rs = mysql_query($query, $conn); + } else { + $rs = mysql_query(str_replace('#~lang~#', $dblang, $query), $conn); + } + } - - $query=''; - } else if(!preg_match("#^(\/\/|--)#", $line)) - { + + $query = ''; + } else if (!preg_match("#^(\/\/|--)#", $line)) { $query .= $line; } } @@ -286,95 +280,92 @@ function _4_Setup() //更新配置 $cquery = "Update `{$dbprefix}sysconfig` set value='{$baseurl}' where varname='cfg_basehost';"; - $dbtype == 'sqlite'? $db->exec($cquery) : mysql_query($cquery,$conn); + $dbtype == 'sqlite' ? $db->exec($cquery) : mysql_query($cquery, $conn); $cquery = "Update `{$dbprefix}sysconfig` set value='{$cmspath}' where varname='cfg_cmspath';"; - $dbtype == 'sqlite'? $db->exec($cquery) : mysql_query($cquery,$conn); + $dbtype == 'sqlite' ? $db->exec($cquery) : mysql_query($cquery, $conn); $cquery = "Update `{$dbprefix}sysconfig` set value='{$indexUrl}' where varname='cfg_indexurl';"; - $dbtype == 'sqlite'? $db->exec($cquery) : mysql_query($cquery,$conn); + $dbtype == 'sqlite' ? $db->exec($cquery) : mysql_query($cquery, $conn); $cquery = "Update `{$dbprefix}sysconfig` set value='{$cookieencode}' where varname='cfg_cookie_encode';"; - $dbtype == 'sqlite'? $db->exec($cquery) : mysql_query($cquery,$conn); + $dbtype == 'sqlite' ? $db->exec($cquery) : mysql_query($cquery, $conn); $cquery = "Update `{$dbprefix}sysconfig` set value='{$webname}' where varname='cfg_webname';"; - $dbtype == 'sqlite'? $db->exec($cquery) : mysql_query($cquery,$conn); + $dbtype == 'sqlite' ? $db->exec($cquery) : mysql_query($cquery, $conn); $cquery = "Update `{$dbprefix}sysconfig` set value='{$adminmail}' where varname='cfg_adminemail';"; - $dbtype == 'sqlite'? $db->exec($cquery) : mysql_query($cquery,$conn); + $dbtype == 'sqlite' ? $db->exec($cquery) : mysql_query($cquery, $conn); //增加管理员帐号 - $adminquery = "INSERT INTO `{$dbprefix}admin` VALUES (1, 10, '$adminuser', '".substr(md5($adminpwd),5,20)."', 'admin', '', '', 0, '".time()."', '127.0.0.1');"; - $dbtype == 'sqlite'? $db->exec($adminquery) : mysql_query($adminquery,$conn); + $adminquery = "INSERT INTO `{$dbprefix}admin` VALUES (1, 10, '$adminuser', '" . substr(md5($adminpwd), 5, 20) . "', 'admin', '', '', 0, '" . time() . "', '127.0.0.1');"; + $dbtype == 'sqlite' ? $db->exec($adminquery) : mysql_query($adminquery, $conn); //关连前台会员帐号 $adminquery = "INSERT INTO `{$dbprefix}member` (`mid`,`mtype`,`userid`,`pwd`,`uname`,`sex`,`rank`,`money`,`email`, `scores` ,`matt` ,`face`,`safequestion`,`safeanswer` ,`jointime` ,`joinip` ,`logintime` ,`loginip` ) - VALUES ('1','个人','$adminuser','".md5($adminpwd)."','$adminuser','男','100','0','','10000','10','','0','','".time()."','','0',''); "; - $dbtype == 'sqlite'? $db->exec($adminquery) : mysql_query($adminquery,$conn); + VALUES ('1','个人','$adminuser','" . md5($adminpwd) . "','$adminuser','男','100','0','','10000','10','','0','','" . time() . "','','0',''); "; + $dbtype == 'sqlite' ? $db->exec($adminquery) : mysql_query($adminquery, $conn); $adminquery = "INSERT INTO `{$dbprefix}member_person` (`mid`,`onlynet`,`sex`,`uname`,`qq`,`msn`,`tel`,`mobile`,`place`,`oldplace`,`birthday`,`star`, `income` , `education` , `height` , `bodytype` , `blood` , `vocation` , `smoke` , `marital` , `house` ,`drink` , `datingtype` , `language` , `nature` , `lovemsg` , `address`,`uptime`) VALUES ('1', '1', '男', '{$adminuser}', '', '', '', '', '0', '0','1980-01-01', '1', '0', '0', '160', '0', '0', '0', '0', '0', '0','0', '0', '', '', '', '','0'); "; - $dbtype == 'sqlite'? $db->exec($adminquery) : mysql_query($adminquery,$conn); + $dbtype == 'sqlite' ? $db->exec($adminquery) : mysql_query($adminquery, $conn); $adminquery = "INSERT INTO `{$dbprefix}member_tj` (`mid`,`article`,`album`,`archives`,`homecount`,`pagecount`,`feedback`,`friend`,`stow`) VALUES ('1','0','0','0','0','0','0','0','0'); "; - $dbtype == 'sqlite'? $db->exec($adminquery): mysql_query($adminquery,$conn); + $dbtype == 'sqlite' ? $db->exec($adminquery) : mysql_query($adminquery, $conn); $adminquery = "Insert Into `{$dbprefix}member_space`(`mid` ,`pagesize` ,`matt` ,`spacename` ,`spacelogo` ,`spacestyle`, `sign` ,`spacenews`) Values('1','10','0','{$adminuser}的空间','','person','',''); "; - $dbtype == 'sqlite'? $db->exec($adminquery) : mysql_query($adminquery,$conn); - - //安装体验数据 - if($installdemo == 1) - { - if($setupsql = file_get_contents(INSTALL_DEMO_NAME)) - { - $setupsql = preg_replace("#ENGINE=MyISAM#i", 'TYPE=MyISAM', $setupsql); - $sql41tmp = 'ENGINE=MyISAM DEFAULT CHARSET='.$cfg_db_language; - if($mysql_version >= 4.1) { - $setupsql = preg_replace("#TYPE=MyISAM#i", $sql41tmp, $setupsql); - } - $setupsql = preg_replace("#_ROOTURL_#i", $rooturl, $setupsql); - $setupsql = preg_replace("#[\r\n]{1,}#", "\n", $setupsql); - $setupsql = preg_replace('/#@__/i',$dbprefix,$setupsql); - $sqls = preg_split("#;[ \t]{0,}\n#", $setupsql); - foreach($sqls as $sql) { - if(trim($sql)!='') mysql_query($sql,$conn); - } - // 更新栏目缓存 - UpDateCatCache(); - } else { - die("没有体验数据包文件,请检查是否下载."); - } + $dbtype == 'sqlite' ? $db->exec($adminquery) : mysql_query($adminquery, $conn); + + //安装体验数据 + if ($installdemo == 1) { + if ($setupsql = file_get_contents(INSTALL_DEMO_NAME)) { + $setupsql = preg_replace("#ENGINE=MyISAM#i", 'TYPE=MyISAM', $setupsql); + $sql41tmp = 'ENGINE=MyISAM DEFAULT CHARSET=' . $cfg_db_language; + if ($mysql_version >= 4.1) { + $setupsql = preg_replace("#TYPE=MyISAM#i", $sql41tmp, $setupsql); + } + $setupsql = preg_replace("#_ROOTURL_#i", $rooturl, $setupsql); + $setupsql = preg_replace("#[\r\n]{1,}#", "\n", $setupsql); + $setupsql = preg_replace('/#@__/i', $dbprefix, $setupsql); + $sqls = preg_split("#;[ \t]{0,}\n#", $setupsql); + foreach ($sqls as $sql) { + if (trim($sql) != '') { + mysql_query($sql, $conn); + } + + } + // 更新栏目缓存 + UpDateCatCache(); + } else { + die("没有体验数据包文件,请检查是否下载."); + } } //不安装任何可选模块 - if(!isset($modules) || !is_array($modules)) - { + if (!isset($modules) || !is_array($modules)) { //锁定安装程序 - $fp = fopen($insLockfile,'w'); - fwrite($fp,'ok'); + $fp = fopen($insLockfile, 'w'); + fwrite($fp, 'ok'); fclose($fp); - include('./templates/step-5.html'); + include './templates/step-5.html'; exit(); - } - else - { - $module = join(',',$modules); - $fp = fopen($moduleCacheFile,'w'); - fwrite($fp,'<'.'?php'."\r\n"); - fwrite($fp,'$selModule = "'.$module.'"; '."\r\n"); - fwrite($fp,'?'.'>'); + } else { + $module = join(',', $modules); + $fp = fopen($moduleCacheFile, 'w'); + fwrite($fp, '<' . '?php' . "\r\n"); + fwrite($fp, '$selModule = "' . $module . '"; ' . "\r\n"); + fwrite($fp, '?' . '>'); //如果不能写入缓存文件,退出模块安装 - if(!$fp) - { + if (!$fp) { //锁定安装程序 - $fp = fopen($insLockfile,'w'); - fwrite($fp,'ok'); + $fp = fopen($insLockfile, 'w'); + fwrite($fp, 'ok'); fclose($fp); $errmsg = "由于无法写入模块缓存,安装可选模块失败,请登录后在模块管理处安装。"; - include('./templates/step-5.html'); + include './templates/step-5.html'; exit(); } fclose($fp); - include('./templates/step-4.html'); + include './templates/step-4.html'; exit(); } exit(); @@ -383,8 +374,7 @@ function _4_Setup() 安装可选模块 function _5_SetupModule() ------------------------*/ -else if($step==5) -{ +else if ($step == 5) { header("location:module-install.php"); exit(); } @@ -392,23 +382,19 @@ function _5_SetupModule() 检测数据库是否有效 function _10_TestDbPwd() ------------------------*/ -else if($step==10) -{ +else if ($step == 10) { header("Pragma:no-cache\r\n"); header("Cache-Control:no-cache\r\n"); header("Expires:0\r\n"); - $conn = @mysql_connect($dbhost,$dbuser,$dbpwd); - if($conn) - { - if(empty($dbname)){ - echo "信息正确"; - }else{ - $info = mysql_select_db($dbname,$conn)?"数据库已经存在,系统将覆盖数据库":"数据库不存在,系统将自动创建"; - echo $info; - } - } - else - { + $conn = @mysql_connect($dbhost, $dbuser, $dbpwd); + if ($conn) { + if (empty($dbname)) { + echo "信息正确"; + } else { + $info = mysql_select_db($dbname, $conn) ? "数据库已经存在,系统将覆盖数据库" : "数据库不存在,系统将自动创建"; + echo $info; + } + } else { echo "数据库连接失败!"; } @mysql_close($conn); diff --git a/install/install.inc.php b/install/install.inc.php index 1bbc046d..16c2086d 100755 --- a/install/install.inc.php +++ b/install/install.inc.php @@ -8,110 +8,122 @@ */ function RunMagicQuotes(&$str) { - if(!get_magic_quotes_gpc()) { - if( is_array($str) ) - foreach($str as $key => $val) $str[$key] = RunMagicQuotes($val); - else + if (!get_magic_quotes_gpc()) { + if (is_array($str)) { + foreach ($str as $key => $val) { + $str[$key] = RunMagicQuotes($val); + } + } else { $str = addslashes($str); + } + } return $str; } function gdversion() { - //没启用php.ini函数的情况下如果有GD默认视作2.0以上版本 - if(!function_exists('phpinfo')) - { - if(function_exists('imagecreate')) return '2.0'; - else return 0; - } - else - { - ob_start(); - phpinfo(8); - $module_info = ob_get_contents(); - ob_end_clean(); - if(preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i", $module_info,$matches)) { $gdversion_h = $matches[1]; } - else { $gdversion_h = 0; } - return $gdversion_h; - } + //没启用php.ini函数的情况下如果有GD默认视作2.0以上版本 + if (!function_exists('phpinfo')) { + if (function_exists('imagecreate')) { + return '2.0'; + } else { + return 0; + } + + } else { + ob_start(); + phpinfo(8); + $module_info = ob_get_contents(); + ob_end_clean(); + if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i", $module_info, $matches)) {$gdversion_h = $matches[1];} else { $gdversion_h = 0;} + return $gdversion_h; + } } -function GetBackAlert($msg,$isstop=0) +function GetBackAlert($msg, $isstop = 0) { global $s_lang; - $msg = str_replace('"','`',$msg); - if($isstop==1) $msg = "\r\n"; - else $msg = "\r\n"; - $msg = "\r\n".$msg; + $msg = str_replace('"', '`', $msg); + if ($isstop == 1) { + $msg = "\r\n"; + } else { + $msg = "\r\n"; + } + + $msg = "\r\n" . $msg; return $msg; } - function TestWrite($d) { $tfile = '_dedet.txt'; $d = preg_replace("#\/$#", '', $d); - $fp = @fopen($d.'/'.$tfile,'w'); - if(!$fp) return false; - else - { + $fp = @fopen($d . '/' . $tfile, 'w'); + if (!$fp) { + return false; + } else { fclose($fp); - $rs = @unlink($d.'/'.$tfile); - if($rs) return true; - else return false; + $rs = @unlink($d . '/' . $tfile); + if ($rs) { + return true; + } else { + return false; + } + } } function ReWriteConfigAuto() { global $dsql; - $configfile = DEDEDATA.'/config.cache.inc.php'; - if(!is_writeable($configfile)) - { + $configfile = DEDEDATA . '/config.cache.inc.php'; + if (!is_writeable($configfile)) { echo "配置文件'{$configfile}'不支持写入,无法修改系统配置参数!"; //ClearAllLink(); exit(); } - $fp = fopen($configfile,'w'); - flock($fp,3); - fwrite($fp,"<"."?php\r\n"); + $fp = fopen($configfile, 'w'); + flock($fp, 3); + fwrite($fp, "<" . "?php\r\n"); $dsql->SetQuery("Select `varname`,`type`,`value`,`groupid` From `#@__sysconfig` order by aid asc "); $dsql->Execute(); - while($row = $dsql->GetArray()) - { - if($row['type']=='number') fwrite($fp,"\${$row['varname']} = ".$row['value'].";\r\n"); - else fwrite($fp,"\${$row['varname']} = '".str_replace("'",'',$row['value'])."';\r\n"); + while ($row = $dsql->GetArray()) { + if ($row['type'] == 'number') { + fwrite($fp, "\${$row['varname']} = " . $row['value'] . ";\r\n"); + } else { + fwrite($fp, "\${$row['varname']} = '" . str_replace("'", '', $row['value']) . "';\r\n"); + } + } - fwrite($fp,"?".">"); + fwrite($fp, "?" . ">"); fclose($fp); } //更新栏目缓存 function UpDateCatCache() { - global $conn,$cfg_multi_site,$dbprefix; - $cache1 = DEDEDATA."/cache/inc_catalog_base.inc"; - $rs = mysql_query("Select id,reid,channeltype,issend,typename From `".$dbprefix."arctype`", $conn); - - $fp1 = fopen($cache1,'w'); + global $conn, $cfg_multi_site, $dbprefix; + $cache1 = DEDEDATA . "/cache/inc_catalog_base.inc"; + $rs = mysql_query("Select id,reid,channeltype,issend,typename From `" . $dbprefix . "arctype`", $conn); + + $fp1 = fopen($cache1, 'w'); $phph = '?'; $fp1Header = "<{$phph}php\r\nglobal \$cfg_Cs;\r\n\$cfg_Cs=array();\r\n"; - fwrite($fp1,$fp1Header); - while($row=mysql_fetch_array($rs)) - { + fwrite($fp1, $fp1Header); + while ($row = mysql_fetch_array($rs)) { $row['typename'] = base64_encode($row['typename']); - fwrite($fp1,"\$cfg_Cs[{$row['id']}]=array({$row['reid']},{$row['channeltype']},{$row['issend']},'{$row['typename']}');\r\n"); + fwrite($fp1, "\$cfg_Cs[{$row['id']}]=array({$row['reid']},{$row['channeltype']},{$row['issend']},'{$row['typename']}');\r\n"); } - fwrite($fp1,"{$phph}>"); + fwrite($fp1, "{$phph}>"); fclose($fp1); } -function IsDownLoad($url) +function IsDownLoad($url) { - if(file_exists($url.'.xml')){ - return true; - }else{ - return false; - } -} \ No newline at end of file + if (file_exists($url . '.xml')) { + return true; + } else { + return false; + } +} diff --git a/install/module-install.php b/install/module-install.php index a8590411..fdc79b0d 100755 --- a/install/module-install.php +++ b/install/module-install.php @@ -6,62 +6,59 @@ * @license http://help.dedecms.com/usersguide/license.html * @link http://www.dedecms.com */ -require_once(dirname(__FILE__).'/../include/common.inc.php'); +require_once dirname(__FILE__) . '/../include/common.inc.php'; @set_time_limit(0); $verMsg = '{{.verMsg}}'; $errmsg = ''; -$insLockfile = dirname(__FILE__).'/install_lock.txt'; -$moduleCacheFile = dirname(__FILE__).'/modules.tmp.inc'; -$moduleDir = DEDEROOT.'/data/module'; -$AdminBaseDir = DEDEROOT.'/dede/'; +$insLockfile = dirname(__FILE__) . '/install_lock.txt'; +$moduleCacheFile = dirname(__FILE__) . '/modules.tmp.inc'; +$moduleDir = DEDEROOT . '/data/module'; +$AdminBaseDir = DEDEROOT . '/dede/'; -if(file_exists($insLockfile)) -{ +if (file_exists($insLockfile)) { exit(" 程序已运行安装,如果你确定要重新安装,请先从FTP中删除 install/install_lock.txt!"); } -require_once(DEDEINC.'/dedemodule.class.php'); -require_once(dirname(__FILE__).'/modulescache.php'); -require_once(dirname(__FILE__).'/install.inc.php'); +require_once DEDEINC . '/dedemodule.class.php'; +require_once dirname(__FILE__) . '/modulescache.php'; +require_once dirname(__FILE__) . '/install.inc.php'; -if(empty($step)) $step = 0; +if (empty($step)) { + $step = 0; +} //完成安装 -if($step==9999) -{ +if ($step == 9999) { ReWriteConfigAuto(); UpDateCatCache(); - include('./templates/step-5.html'); + include './templates/step-5.html'; exit(); } //用户选择的模块列表缓存文件 -if(!file_exists($moduleCacheFile)) -{ - $msg = "由于无法找到模块缓存文件,安装可选模块失败,请登录后在模块管理处安装。

    "; - $msg .= "点击此完成安装 >>"; - ShowMsg($msg,'javascript:;'); +if (!file_exists($moduleCacheFile)) { + $msg = "由于无法找到模块缓存文件,安装可选模块失败,请登录后在模块管理处安装。

    "; + $msg .= "点击此完成安装 >>"; + ShowMsg($msg, 'javascript:;'); exit(); } //模块文件夹权限 -if(!TestWrite($moduleDir)) -{ - $msg = "目录 {$moduleDir} 不支持写入,不能安装模块,请登录后在模块管理处安装。

    "; - $msg .= "点击此完成安装 >>"; - ShowMsg($msg,"javascript:;"); +if (!TestWrite($moduleDir)) { + $msg = "目录 {$moduleDir} 不支持写入,不能安装模块,请登录后在模块管理处安装。

    "; + $msg .= "点击此完成安装 >>"; + ShowMsg($msg, "javascript:;"); exit(); } -include($moduleCacheFile); -$modules = split(',',$selModule); +include $moduleCacheFile; +$modules = split(',', $selModule); $totalMod = count($modules); -if($step >= $totalMod) -{ - $msg = "完成所有模块的安装!

    "; - $msg .= "点击此进行下一步操作 >>"; - ShowMsg($msg,'javascript:;'); +if ($step >= $totalMod) { + $msg = "完成所有模块的安装!

    "; + $msg .= "点击此进行下一步操作 >>"; + ShowMsg($msg, 'javascript:;'); exit(); } $moduleHash = $modules[$step]; @@ -71,7 +68,7 @@ $minfos = $dm->GetModuleInfo($moduleHash); extract($minfos, EXTR_SKIP); -$menustring = addslashes($dm->GetSystemFile($moduleHash,'menustring')); +$menustring = addslashes($dm->GetSystemFile($moduleHash, 'menustring')); $query = "INSERT INTO `#@__sys_module`(`hashcode` , `modname` , `indexname` , `indexurl` , `ismember` , `menustring` ) VALUES ('$moduleHash' , '$name' , '$indexname' , '$indexurl' , '$ismember' , '$menustring' ) "; @@ -79,42 +76,46 @@ $rs = $dsql->ExecuteNoneQuery("Delete From `#@__sys_module` where hashcode like '$moduleHash' "); $rs = $dsql->ExecuteNoneQuery($query); -if(!$rs) -{ - $msg = "保存数据库信息失败,无法完成你选择的模块安装!

    "; - $msg .= "点击此进行下一步操作 >>"; +if (!$rs) { + $msg = "保存数据库信息失败,无法完成你选择的模块安装!

    "; + $msg .= "点击此进行下一步操作 >>"; exit(); } //写文件 -$dm->WriteFiles($moduleHash,1); -$dm->WriteSystemFile($moduleHash,'readme'); +$dm->WriteFiles($moduleHash, 1); +$dm->WriteSystemFile($moduleHash, 'readme'); -$setupsql = $dm->GetSystemFile($moduleHash,'setupsql40'); +$setupsql = $dm->GetSystemFile($moduleHash, 'setupsql40'); //运行SQL -$mysql_version = $dsql->GetVersion(TRUE); +$mysql_version = $dsql->GetVersion(true); $setupsql = preg_replace("#ENGINE=MyISAM#i", 'TYPE=MyISAM', $setupsql); -$sql41tmp = 'ENGINE=MyISAM DEFAULT CHARSET='.$cfg_db_language; +$sql41tmp = 'ENGINE=MyISAM DEFAULT CHARSET=' . $cfg_db_language; -if($mysql_version >= 4.1) { +if ($mysql_version >= 4.1) { $setupsql = preg_replace("#TYPE=MyISAM#i", $sql41tmp, $setupsql); -} +} //_ROOTURL_ -if($cfg_cmspath=='/') $cfg_cmspath = ''; +if ($cfg_cmspath == '/') { + $cfg_cmspath = ''; +} -$rooturl = $cfg_basehost.$cfg_cmspath; +$rooturl = $cfg_basehost . $cfg_cmspath; $setupsql = preg_replace("#_ROOTURL_#i", $rooturl, $setupsql); -$setupsql = preg_replace("#[\r\n]{1,}#", "\n", $setupsql); +$setupsql = preg_replace("#[\r\n]{1,}#", "\n", $setupsql); $sqls = preg_split("#;[ \t]{0,}\n#", $setupsql); -foreach($sqls as $sql) { - if(trim($sql)!='') $dsql->executenonequery($sql); +foreach ($sqls as $sql) { + if (trim($sql) != '') { + $dsql->executenonequery($sql); + } + } $dm->Clear(); $step = $step + 1; ShowMsg("模块 {$name} 安装完成,准备下一模块安装...", "module-install.php?step={$step}"); -exit(); \ No newline at end of file +exit(); diff --git a/install/modulescache.php b/install/modulescache.php index ae5fe8b4..6426367d 100755 --- a/install/modulescache.php +++ b/install/modulescache.php @@ -1,18 +1,17 @@ \ No newline at end of file +$GLOBALS['allmodules']['0a7bea5dbe571d35def883cbec796437'] = '0a7bea5dbe571d35def883cbec796437.xml'; +$GLOBALS['allmodules']['0cce60bc0238aa03804682c801584991'] = '0cce60bc0238aa03804682c801584991.xml'; +$GLOBALS['allmodules']['1f35620fb42d452fa2bdc1dee1690f92'] = '1f35620fb42d452fa2bdc1dee1690f92.xml'; +$GLOBALS['allmodules']['572606600345b1a4bb8c810bbae434cc'] = '572606600345b1a4bb8c810bbae434cc.xml'; +$GLOBALS['allmodules']['59155be87ea60c5c65ec1f7a46a0fc9d'] = '59155be87ea60c5c65ec1f7a46a0fc9d.xml'; +$GLOBALS['allmodules']['72ffa6fabe3c236f9238a2b281bc0f93'] = '72ffa6fabe3c236f9238a2b281bc0f93.xml'; +$GLOBALS['allmodules']['7badb72a3ff79af2a7112beee60cb970'] = '7badb72a3ff79af2a7112beee60cb970.xml'; +$GLOBALS['allmodules']['867af26e9c1ccf22a1cf67e756cf5acc'] = '867af26e9c1ccf22a1cf67e756cf5acc.xml'; +$GLOBALS['allmodules']['8964eda9013d1df0afea08ed63243436'] = '8964eda9013d1df0afea08ed63243436.xml'; +$GLOBALS['allmodules']['acb8b88eb4a6d4bfc375c18534f9439e'] = 'acb8b88eb4a6d4bfc375c18534f9439e.xml'; +$GLOBALS['allmodules']['b437d85a7a7bc778c9c79b5ec36ab9aa'] = 'b437d85a7a7bc778c9c79b5ec36ab9aa.xml'; +$GLOBALS['allmodules']['be722dbfa3cb3cb5628aab2d767ff62e'] = 'be722dbfa3cb3cb5628aab2d767ff62e.xml'; +$GLOBALS['allmodules']['c10bb6ac52082ab3e669b4814b44a6f1'] = 'c10bb6ac52082ab3e669b4814b44a6f1.xml'; +$GLOBALS['allmodules']['dfcb5cd4d7bc0e3f7eb655e62dd6bc64'] = 'dfcb5cd4d7bc0e3f7eb655e62dd6bc64.xml'; +$GLOBALS['allmodules']['8a4773468b800900dcfefbc5988833ed'] = '8a4773468b800900dcfefbc5988833ed.xml'; diff --git a/install/style.css b/install/style.css index 66a30868..05ecad12 100755 --- a/install/style.css +++ b/install/style.css @@ -1,287 +1,284 @@ @import "tablebox.css"; -*{ - padding:0px; - margin:0px; +* { + padding: 0px; + margin: 0px; } -body{ - font-family:Verdana, Arial, Helvetica, sans-serif; - font-size:12px; - background:url(images/top-bg.png) left top repeat-x; - background-color:#FFF; +body { + font-family: Verdana, Arial, Helvetica, sans-serif; + font-size: 12px; + background: url(images/top-bg.png) left top repeat-x; + background-color: #fff; } -ul{ - list-style:none; +ul { + list-style: none; } -a{ - color:#06C; +a { + color: #06c; } -a:hover{ - color:#669900; - text-decoration:none; +a:hover { + color: #669900; + text-decoration: none; } -input,button,select{ - vertical-align:middle; +input, +button, +select { + vertical-align: middle; } -.fc-690{ - color:#690; +.fc-690 { + color: #690; } -.fs-14{ - font-size:14px; +.fs-14 { + font-size: 14px; } -.top{ - width:960px; - height:72px; - overflow:hidden; - margin:0px auto; -} -.top .top-logo{ - width:280px; - height:72px; - float:left; - padding-left:10px; - background:url(images/top-logo.png) 10px 0px no-repeat; - overflow:hidden; -} -.top .top-logo h1{ - font-size:0px; - line-height:1000%; -} -.top .top-link{ - height:15px; - padding:12px 12px 0px 0px; - overflow:hidden; -} -.top .top-link ul{ - height:15px; - float:right; - overflow:hidden; -} -.top .top-link ul li{ - float:left; - padding-left:10px; - padding-right:10px; - border-left:1px solid #E8F5E3; - margin-left:-1px; - line-height:14px; -} -.top .top-link ul li a{ - text-decoration:none; - color:#555; -} -.top .top-version{ - height:40px; - float:right; - padding:7px 12px 0px 0px; -} -.top .top-version h2{ - color:#E8F5E3; - font-size:26px; - font-style:italic; - cursor:default; +.top { + width: 960px; + height: 72px; + overflow: hidden; + margin: 0px auto; +} +.top .top-logo { + width: 280px; + height: 72px; + float: left; + padding-left: 10px; + background: url(images/top-logo.png) 10px 0px no-repeat; + overflow: hidden; +} +.top .top-logo h1 { + font-size: 0px; + line-height: 1000%; +} +.top .top-link { + height: 15px; + padding: 12px 12px 0px 0px; + overflow: hidden; +} +.top .top-link ul { + height: 15px; + float: right; + overflow: hidden; +} +.top .top-link ul li { + float: left; + padding-left: 10px; + padding-right: 10px; + border-left: 1px solid #e8f5e3; + margin-left: -1px; + line-height: 14px; +} +.top .top-link ul li a { + text-decoration: none; + color: #555; +} +.top .top-version { + height: 40px; + float: right; + padding: 7px 12px 0px 0px; +} +.top .top-version h2 { + color: #e8f5e3; + font-size: 26px; + font-style: italic; + cursor: default; } -.main{ - width:900px; - margin:14px auto 0px; +.main { + width: 900px; + margin: 14px auto 0px; } -.main .pleft{ - width:168px; - float:left; - cursor:default; - padding-top:6px; +.main .pleft { + width: 168px; + float: left; + cursor: default; + padding-top: 6px; } -.main .pright{ - width:720px; - float:right; +.main .pright { + width: 720px; + float: right; } - -.pr-title{ - width:720px; - height:22px; - margin:8px auto 0px; - background:url(images/boxtitle_bg.gif) 0px 20px repeat-x; - overflow:hidden; -} -.pr-title h3{ - width:158px; - height:22px; - line-height:22px; - overflow:hidden; - display:block; - font-size:12px; - padding-top:1px; - text-indent:10px; - background:url(images/boxtitle_bg.gif) 0px -2px no-repeat; - letter-spacing:2px; - color:#6D8A4F; - font-weight:bold; +.pr-title { + width: 720px; + height: 22px; + margin: 8px auto 0px; + background: url(images/boxtitle_bg.gif) 0px 20px repeat-x; + overflow: hidden; +} +.pr-title h3 { + width: 158px; + height: 22px; + line-height: 22px; + overflow: hidden; + display: block; + font-size: 12px; + padding-top: 1px; + text-indent: 10px; + background: url(images/boxtitle_bg.gif) 0px -2px no-repeat; + letter-spacing: 2px; + color: #6d8a4f; + font-weight: bold; } -.t1{ - width:162px; -} -.t1 dt{ - width:162px; - height:25px; - line-height:25px; - background:url(images/leftbox-tbg.png) no-repeat; - font-weight:bold; - color:#7D9F5C; - text-indent:10px; - letter-spacing:2px; -} -.t1 dd{ - width:160px; - background-color:#FAFDF9; - border:1px solid #E0ECD4; -} -.t1 dd ul{ - width:158px; - border:1px solid #FFF; - overflow:hidden; - padding:10px 0px; - background:url(images/step-ico-bg.png) 20px 21px no-repeat; -} -.t1 dd ul li{ - height:40px; - line-height:36px; - text-indent:52px; - display:block; - color:#888; - font-size:14px; -} -.t1 dd ul li.succeed{ - color:#690; - background:url(images/ico-step-succeed.png) 23px 14px no-repeat; -} -.t1 dd ul li.now{ - color:#FF9900; - font-weight:bold; - background:url(images/ico-step-now.png) 23px 14px no-repeat; +.t1 { + width: 162px; +} +.t1 dt { + width: 162px; + height: 25px; + line-height: 25px; + background: url(images/leftbox-tbg.png) no-repeat; + font-weight: bold; + color: #7d9f5c; + text-indent: 10px; + letter-spacing: 2px; +} +.t1 dd { + width: 160px; + background-color: #fafdf9; + border: 1px solid #e0ecd4; +} +.t1 dd ul { + width: 158px; + border: 1px solid #fff; + overflow: hidden; + padding: 10px 0px; + background: url(images/step-ico-bg.png) 20px 21px no-repeat; +} +.t1 dd ul li { + height: 40px; + line-height: 36px; + text-indent: 52px; + display: block; + color: #888; + font-size: 14px; +} +.t1 dd ul li.succeed { + color: #690; + background: url(images/ico-step-succeed.png) 23px 14px no-repeat; +} +.t1 dd ul li.now { + color: #ff9900; + font-weight: bold; + background: url(images/ico-step-now.png) 23px 14px no-repeat; } -.install-msg{ - padding:10px 20px; - color:#777; - line-height:31px; - font-size:14px; - overflow:hidden; - clear:both; - +.install-msg { + padding: 10px 20px; + color: #777; + line-height: 31px; + font-size: 14px; + overflow: hidden; + clear: both; } - -.pr-agreement{ - padding:16px; - line-height:21px; - color:#666; - height:300px; - overflow-y:scroll; -} -.pr-agreement strong{ - display:block; - color:#333; - line-height:27px; - margin-top:6px; -} -.pr-agreement p{ - text-indent:30px; +.pr-agreement { + padding: 16px; + line-height: 21px; + color: #666; + height: 300px; + overflow-y: scroll; +} +.pr-agreement strong { + display: block; + color: #333; + line-height: 27px; + margin-top: 6px; +} +.pr-agreement p { + text-indent: 30px; } - -.btn-box{ - margin-top:15px; - border-top:1px solid #DDD; - padding:10px 6px; - vertical-align:middle; -} -.btn-next{ - width:104px; - height:34px; - border:none; - background:url(images/but_next.gif) no-repeat; - cursor:pointer; - margin-left:10px; - overflow:hidden; - font-size:0px; - line-height:100px; -} -.btn-back{ - width:104px; - height:34px; - border:none; - background:url(images/but_back.gif) no-repeat; - cursor:pointer; - overflow:hidden; - font-size:0px; - line-height:100px; +.btn-box { + margin-top: 15px; + border-top: 1px solid #ddd; + padding: 10px 6px; + vertical-align: middle; +} +.btn-next { + width: 104px; + height: 34px; + border: none; + background: url(images/but_next.gif) no-repeat; + cursor: pointer; + margin-left: 10px; + overflow: hidden; + font-size: 0px; + line-height: 100px; +} +.btn-back { + width: 104px; + height: 34px; + border: none; + background: url(images/but_back.gif) no-repeat; + cursor: pointer; + overflow: hidden; + font-size: 0px; + line-height: 100px; } - -#readpact{ - *margin-top:-4px; - margin-right:4px; +#readpact { + *margin-top: -4px; + margin-right: 4px; } -.over-link{ - padding:0px 40px; - line-height:41px; - overflow:hidden; - clear:both; -} -.over-link a{ - line-height:14px; - padding:6px 20px; - border-style:solid; - border-width:1px; - border-color:#EEE #CCC #CCC #EEE; - background:#FAFAFA; - color:#333; - display:block; - float:left; - margin-right:20px; - text-decoration:none; +.over-link { + padding: 0px 40px; + line-height: 41px; + overflow: hidden; + clear: both; +} +.over-link a { + line-height: 14px; + padding: 6px 20px; + border-style: solid; + border-width: 1px; + border-color: #eee #ccc #ccc #eee; + background: #fafafa; + color: #333; + display: block; + float: left; + margin-right: 20px; + text-decoration: none; } -.olink a{ - line-height:14px; - padding:2px 20px; - border-style:solid; - border-width:1px; - border-color:#EEE #CCC #CCC #EEE; - background:#EAF4DD; - color:#333; - display:block; - margin-left:8px; - float:left; - width:55px; - margin-right:20px; - text-decoration:none; +.olink a { + line-height: 14px; + padding: 2px 20px; + border-style: solid; + border-width: 1px; + border-color: #eee #ccc #ccc #eee; + background: #eaf4dd; + color: #333; + display: block; + margin-left: 8px; + float: left; + width: 55px; + margin-right: 20px; + text-decoration: none; } .waitpage { - top:0; - left:0; - filter:Alpha(opacity=70); - -moz-opacity:0.7; - position:absolute; - z-index:10000; - background:url(images/loading1.gif) #ababab no-repeat center 200px; - width:100%; - height:2500px; - display:none; + top: 0; + left: 0; + filter: Alpha(opacity=70); + -moz-opacity: 0.7; + position: absolute; + z-index: 10000; + background: url(images/loading1.gif) #ababab no-repeat center 200px; + width: 100%; + height: 2500px; + display: none; } .divpre { - filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale); + filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale); } .modulesel { - width:120px; - margin-right:8px; - float:left; -} \ No newline at end of file + width: 120px; + margin-right: 8px; + float: left; +} diff --git a/install/tablebox.css b/install/tablebox.css index 97479234..fb5ad4de 100755 --- a/install/tablebox.css +++ b/install/tablebox.css @@ -1,162 +1,154 @@ -input{ - vertical-align:middle; - margin-right:3px; - font-size:12px; -} -textarea{ - vertical-align:top; - font-size:12px; - line-height:156%; - border:1px solid #AAA; - padding:3px; - letter-spacing:1px; - word-break:break-all; - overflow-y:auto; -} -.input-txt{ - padding:4px 8px 4px 6px; - border:1px solid #AAA; - font-size:12px; - color:#000; - width:200px; -} - -.textipt_on{ - border:1px solid #F90; -} - - -hr{ - height:1px; - line-height:1px; - overflow:hidden; - border-width:1px 0px 0px 0px ; - border-top:1px solid #E6E6E6;/*兼容Opera*/ - } +input { + vertical-align: middle; + margin-right: 3px; + font-size: 12px; +} +textarea { + vertical-align: top; + font-size: 12px; + line-height: 156%; + border: 1px solid #aaa; + padding: 3px; + letter-spacing: 1px; + word-break: break-all; + overflow-y: auto; +} +.input-txt { + padding: 4px 8px 4px 6px; + border: 1px solid #aaa; + font-size: 12px; + color: #000; + width: 200px; +} + +.textipt_on { + border: 1px solid #f90; +} + +hr { + height: 1px; + line-height: 1px; + overflow: hidden; + border-width: 1px 0px 0px 0px; + border-top: 1px solid #e6e6e6; /*兼容Opera*/ +} hr:empty { - margin:8px 0px 7px 0px !important; - margin:0px; + margin: 8px 0px 7px 0px !important; + margin: 0px; } -small{ - font-size:12px; +small { + font-size: 12px; } -.moncolor td{ - background:#FFC; +.moncolor td { + background: #ffc; } -.twbox{ - width:706px; - border:1px solid #CFDCC9; - font-size:12px; - overflow:hidden; - margin:8px auto; - +.twbox { + width: 706px; + border: 1px solid #cfdcc9; + font-size: 12px; + overflow: hidden; + margin: 8px auto; } - -.twbox thead tr td{ - background:url(body_title_bg.gif) -1px -1px repeat-x; - height:31px; - line-height:31px; - text-indent:10px; +.twbox thead tr td { + background: url(body_title_bg.gif) -1px -1px repeat-x; + height: 31px; + line-height: 31px; + text-indent: 10px; } -.twbox thead tr td strong{ - letter-spacing:2px; - margin-right:14px; - color:#FFF; - font-size:14px; +.twbox thead tr td strong { + letter-spacing: 2px; + margin-right: 14px; + color: #fff; + font-size: 14px; } - -.twbox thead tr td span{ - color:#CDA; +.twbox thead tr td span { + color: #cda; } - -.twbox thead tr td p{ - height:31px; - display:inline; - float:right; - margin:-31px 10px 0 0; - overflow:hidden; +.twbox thead tr td p { + height: 31px; + display: inline; + float: right; + margin: -31px 10px 0 0; + overflow: hidden; } -.twbox thead tr td p *{ - float:right; +.twbox thead tr td p * { + float: right; } -.twbox thead tr td a.thlink{ - color:#FFF; +.twbox thead tr td a.thlink { + color: #fff; } -.twbox thead tr td a.thlink:hover{ - color:#FFFF00; - text-decoration:none; +.twbox thead tr td a.thlink:hover { + color: #ffff00; + text-decoration: none; } - .twbox tbody { - overflow:hidden; - text-align:left; + overflow: hidden; + text-align: left; } -.twbox tbody tr th{ - background:#F9FCEF; - color:#6D8A4F; - line-height:21px; - height:21px; - text-indent:30px; - font-weight:normal; - border-bottom:1px solid #EFF7D8; - letter-spacing:2px; +.twbox tbody tr th { + background: #f9fcef; + color: #6d8a4f; + line-height: 21px; + height: 21px; + text-indent: 30px; + font-weight: normal; + border-bottom: 1px solid #eff7d8; + letter-spacing: 2px; } -.twbox tbody tr td{ - padding:7px; - border-bottom:1px solid #F2F2F2; - color:#333; - vertical-align:top; +.twbox tbody tr td { + padding: 7px; + border-bottom: 1px solid #f2f2f2; + color: #333; + vertical-align: top; } -.twbox tbody tr td p{ - line-height:21px; +.twbox tbody tr td p { + line-height: 21px; } -.twbox tbody tr td p strong img{ - vertical-align:middle; +.twbox tbody tr td p strong img { + vertical-align: middle; } -.twbox tbody tr td img{ - vertical-align:top; - margin:0px 10px 5px 0px; - +.twbox tbody tr td img { + vertical-align: top; + margin: 0px 10px 5px 0px; } -.twbox tbody tr td small{ - color:#888; +.twbox tbody tr td small { + color: #888; } -.twbox tfoot tr td{ - padding:10px; - line-height:25px; - text-align:center; +.twbox tfoot tr td { + padding: 10px; + line-height: 25px; + text-align: center; } -.twbox tfoot tr td p{ - line-height:21px; - margin-bottom:10px; +.twbox tfoot tr td p { + line-height: 21px; + margin-bottom: 10px; } -input.but{ - height:26px; - padding-left:6px; - padding-right:6px; - line-height:26px; - font-weight:bold; - letter-spacing:1px; - color:#FFF; - background-color:#FC3; +input.but { + height: 26px; + padding-left: 6px; + padding-right: 6px; + line-height: 26px; + font-weight: bold; + letter-spacing: 1px; + color: #fff; + background-color: #fc3; } -.onetd{ - width:120px; - text-align:right; - line-height:25px; +.onetd { + width: 120px; + text-align: right; + line-height: 25px; } - diff --git a/install/templates/step-1.html b/install/templates/step-1.html index 065447c8..b8e28b70 100755 --- a/install/templates/step-1.html +++ b/install/templates/step-1.html @@ -1,82 +1,98 @@ - + + - -安装程序 - 织梦内容管理系统<?php echo $verMsg; ?> - + + 安装程序 - 织梦内容管理系统 + <?php echo $verMsg; ?> + + -
    - - -
    - -

    DedeCMS

    +
    + + +
    + +

    DedeCMS + +

    +
    -
    -
    -
    -
    -
    安装步骤
    -
    -
      -
    • 许可协议
    • -
    • 环境检测
    • -
    • 参数配置
    • -
    • 正在安装
    • -
    • 安装完成
    • -
    -
    -
    -
    -
    -

    阅读许可协议

    -
    +
    +
    +
    +
    安装步骤
    +
    +
      +
    • 许可协议
    • +
    • 环境检测
    • +
    • 参数配置
    • +
    • 正在安装
    • +
    • 安装完成
    • +
    +
    +
    +
    +
    +
    +

    阅读许可协议

    +
    +

    版权所有 (c) 2004-2020,DedeCMS.com 保留所有权利。

    -

    感谢您选择织梦内容管理系统(以下简称DedeCMS),DedeCMS是目前国内专业、便捷、稳定的中小型门户网站建设解决方案之一,基于 PHP + MySQL 的技术开发,全部源码开放。

    -

    DedeCMS 的官方网址是: www.dedecms.com Github: github.com/dedecms

    +

    感谢您选择织梦内容管理系统(以下简称DedeCMS),DedeCMS是目前国内专业、便捷、稳定的中小型门户网站建设解决方案之一,基于 PHP + MySQL 的技术开发,全部源码开放。

    +

    DedeCMS 的官方网址是: www.dedecms.com Github: github.com/dedecms

    为了使你正确并合法的使用本软件,请你在使用前务必阅读清楚下面的协议条款:

    - 一、本授权协议适用且仅适用于 DedeCMS 5.x.x 版本,DedeCMS官方对本授权协议的最终解释权。 - 二、协议许可的权利 + 一、本授权协议适用且仅适用于 DedeCMS 5.x.x 版本,DedeCMS官方对本授权协议的最终解释权。 + 二、协议许可的权利

    1、您可以在完全遵守本最终用户授权协议的基础上,将本软件应用于非商业用途,而不必支付软件版权授权费用。

    2、您可以在协议规定的约束和限制范围内修改 DedeCMS 源代码或界面风格以适应您的网站要求。

    3、您拥有使用本软件构建的网站全部内容所有权,并独立承担与这些内容的相关法律义务。

    -

    4、获得商业授权之后,您可以将本软件应用于商业用途,同时依据所购买的授权类型中确定的技术支持内容,自购买时刻起,在技术支持期限内拥有通过指定的方式获得指定范围内的技术支持服务。商业授权用户享有反映和提出意见的权力,相关意见将被作为首要考虑,但没有一定被采纳的承诺或保证。

    - 二、协议规定的约束和限制 +

    4、获得商业授权之后,您可以将本软件应用于商业用途,同时依据所购买的授权类型中确定的技术支持内容,自购买时刻起,在技术支持期限内拥有通过指定的方式获得指定范围内的技术支持服务。商业授权用户享有反映和提出意见的权力,相关意见将被作为首要考虑,但没有一定被采纳的承诺或保证。 +

    + 二、协议规定的约束和限制

    1、未获商业授权之前,不得将本软件用于商业用途(包括但不限于企业网站、经营性网站、以营利为目的或实现盈利的网站)。

    2、未经官方许可,不得对本软件或与之关联的商业授权进行出租、出售、抵押或发放子许可证。

    -

    3、不管你的网站是否整体使用 DedeCMS ,还是部份栏目使用 DedeCMS,在你使用了 DedeCMS 的网站主页上必须加上DedeCMS官方网址(www.dedecms.com)的链接。

    +

    3、不管你的网站是否整体使用 DedeCMS ,还是部份栏目使用 DedeCMS,在你使用了 DedeCMS 的网站主页上必须加上DedeCMS官方网址(www.dedecms.com)的链接。

    4、未经官方许可,禁止在 DedeCMS的整体或任何部分基础上以发展任何派生版本、修改版本或第三方版本用于重新分发。

    5、如果您未能遵守本协议的条款,您的授权将被终止,所被许可的权利将被收回,并承担相应法律责任。

    - 三、有限担保和免责声明 + 三、有限担保和免责声明

    1、本软件及所附带的文件是作为不提供任何明确的或隐含的赔偿或担保的形式提供的。

    2、用户出于自愿而使用本软件,您必须了解使用本软件的风险,在尚未购买产品技术服务之前,我们不承诺对免费用户提供任何形式的技术支持、使用担保,也不承担任何因使用本软件而产生问题的相关责任。

    -

    3、电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装 DedeCMS,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。

    +

    3、电子文本形式的授权协议如同双方书面签署的协议一样,具有完全的和等同的法律效力。您一旦开始确认本协议并安装 + DedeCMS,即被视为完全理解并接受本协议的各项条款,在享有上述条款授予的权力的同时,受到相关的约束和限制。协议许可范围以外的行为,将直接违反本授权协议并构成侵权,我们有权随时终止授权,责令停止损害,并保留追究相关责任的权力。 +

    4、如果本软件带有其它软件的整合API示范例子包,这些文件版权不属于本软件官方,并且这些文件是没经过授权发布的,请参考相关软件的使用许可合法的使用。

    协议发布时间: 2008年1月18日

    版本最新更新: {UpdateVersionDate}

    -
    -
    - - +
    +
    + + +
    -
    -
    +
    -
    +
    - + + \ No newline at end of file diff --git a/install/templates/step-2.html b/install/templates/step-2.html index 8de1665d..e23c3d99 100755 --- a/install/templates/step-2.html +++ b/install/templates/step-2.html @@ -1,146 +1,179 @@ - + + - -安装程序 - 织梦内容管理系统<?php echo $verMsg; ?> - + + 安装程序 - 织梦内容管理系统 + <?php echo $verMsg; ?> + + -
    - - -
    - -

    DEDECMS

    -
    -
    +
    + -
    +
    -
    +
    - + + \ No newline at end of file diff --git a/install/templates/step-3.html b/install/templates/step-3.html index eaaeb531..1043ccc1 100755 --- a/install/templates/step-3.html +++ b/install/templates/step-3.html @@ -1,203 +1,263 @@ - + + - -安装程序 - 织梦内容管理系统<?php echo $verMsg; ?> - - - + function DoInstall() { + //$o('postloader').style.display = 'block'; + document.form1.submit(); + } + + function randpwd() { + // >= IE8 + document.querySelector("input[name='adminpwd']").value = Math.random().toString(36).slice(-8) + Math.random().toString(36).slice(-8); + } + --> + + + -
    -
    - -
    - - -
    - -

    DEDECMS

    -
    -
    +
    + + +
    + +
    +
    +
    + - + + \ No newline at end of file diff --git a/install/templates/step-4.html b/install/templates/step-4.html index 557dd912..531b0684 100755 --- a/install/templates/step-4.html +++ b/install/templates/step-4.html @@ -1,55 +1,66 @@ - + + - -安装程序 - 织梦内容管理系统<?php echo $verMsg; ?> - + + 安装程序 - 织梦内容管理系统 + <?php echo $verMsg; ?> + + + -
    - - -
    - -

    DEDECMS

    -
    -
    - -
    -
    -
    -
    安装步骤
    -
    -
      -
    • 许可协议
    • -
    • 环境检测
    • -
    • 参数配置
    • -
    • 安装模块
    • -
    • 安装完成
    • -
    -
    -
    +
    + + +
    + +

    DEDECMS + +

    +
    -
    -

    正在安装模块

    -
    - + +
    +
    +
    +
    安装步骤
    +
    +
      +
    • 许可协议
    • +
    • 环境检测
    • +
    • 参数配置
    • +
    • 安装模块
    • +
    • 安装完成
    • +
    +
    +
    +
    +
    +
    +

    正在安装模块

    +
    +
    + +
    -
    -
    -
    +
    +
    - + + \ No newline at end of file diff --git a/install/templates/step-5.html b/install/templates/step-5.html index 844118cb..59e76b1e 100755 --- a/install/templates/step-5.html +++ b/install/templates/step-5.html @@ -1,70 +1,80 @@ - + + - -安装程序 - 织梦内容管理系统<?php echo $verMsg; ?> - + + 安装程序 - 织梦内容管理系统 + <?php echo $verMsg; ?> + + + -
    - - -
    - -

    DEDECMS

    -
    -
    +
    +