code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>会员</title> <meta content="会员中心" name="keywords"> <meta content="会员中心" name="description"> <base href="{:$smarty.const.PUBLIC_DIR}/"> <script language="JavaScript" src="common/js/jquery.js"></script> <script language="JavaScript" src="member/js/css.js"></script> <link href="member/style/member.css" rel="stylesheet" type="text/css"> </head> <body style="background-color:#fff"> {:include file="./head.tpl"} <div id="main"> <form> <table cellpadding="0" cellspacing="1" class="table_reg"> <caption> 新用户注册 </caption> <tr> <th width="12%">会员类型</th> <td width="*"><input name="groupId" value="1" type="radio" class="posted" />个人 <input name="groupId" value="2" type="radio" class="posted" checked="checked" class="posted" />企业</td> </tr> <tr> <th width="12%">用户名:</th> <td width="*"><input type="text" name="username" id="username" value="" size="20" maxlength="20" class="posted" /> 4-20字母、数字、下划线或减号的组合, 首字符必须为字母或数字</td> </tr> <tr> <th>密 码:</th> <td><input name="password" type="password" id="password" size="20" maxlength="16" class="posted" /> 6-20位不含空格的字符串</td> </tr> <tr> <th>Email地址:</th> <td><input name="email" type="text" id="email" size="30" class="posted" /> </td> </tr> <tr> <th>验证码:</th> <td><input name="validateCode" type="text" size="6" maxlength="6" class="posted" /> <img name="" align="absmiddle" style="cursor:pointer;" id="validateImage" src="{:$smarty.const.BOOT_URL}/common/validateCode" alt="点击重新获取验证码!" onclick="setValidateCode();" /> </td> </tr> <tr> <th></th> <td> <input type="submit" name="dosubmit" id="registerform" value=" 注 册 " /> <input type="reset" name="reset" value=" 重 置 " /> <a href="{:$smarty.const.BOOT_URL}/member/login">已经注册过了?马上登陆...</a> </td> </tr> </table> </form> <span id="toggle_pannel"></span> </div> {:include file="./foot.tpl"} <link href="{:$smarty.const.PUBLIC_DIR}/common/style/ui.all.css" rel="stylesheet" type="text/css" /> <script language="javascript" type="text/javascript" src="{:$smarty.const.PUBLIC_DIR}/common/js/jquery.js"></script> <script language="javascript" type="text/javascript" src="{:$smarty.const.PUBLIC_DIR}/common/js/ui.core.js"></script> <script language="javascript" type="text/javascript" src="{:$smarty.const.PUBLIC_DIR}/common/js/ui.draggable.js"></script> <script language="javascript" type="text/javascript" src="{:$smarty.const.PUBLIC_DIR}/common/js/ui.dialog.js"></script> <script language="javascript" type="text/javascript" src="{:$smarty.const.PUBLIC_DIR}/common/js/jquery.post.js"></script> <script language="javascript" type="text/javascript" src="{:$smarty.const.PUBLIC_DIR}/common/js/common.js"></script> <script language="javascript" type="text/javascript"> $(document).ready(function(){ $("form").post({ sendUrl:"{:$smarty.const.BOOT_URL}/member/register/check", trueJs:"redirect('{:$smarty.const.BOOT_URL}/member/login');", falseJs:"setValidateCode();" }); }); function setValidateCode() { $("#validateImage").attr('src','{:$smarty.const.BOOT_URL}/common/validateCode/'+Math.ceil(Math.random()*1000)); } </script> </body> </html>
01cms
01cms/branches/2.0/template/member/register.tpl
Smarty
asf20
3,763
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>会员</title> <meta content="会员中心" name="keywords"> <meta content="会员中心" name="description"> <base href="{:$smarty.const.PUBLIC_DIR}/"> <link href="member/style/member.css" rel="stylesheet" type="text/css"> </head> <body style="background-color:#fff"> {:include file="./head.tpl"} <form> <div id="login"> <div id="login_l"><br /><br /> <div id="login_t"></div> <ul> <li>用户名:<input name="username" type="text" id="username" size="18" class="input posted" /></li> <li>密 码:<input name="password" type="password" id="password" size="18" class="input posted" /></li> <li>验证码:<input name="validateCode" type="text" size="6" maxlength="6" class="input posted" /> <img name="" align="absmiddle" style="cursor:pointer;" id="validateImage" src="{:$smarty.const.BOOT_URL}/common/validateCode" alt="点击重新获取验证码!" onclick="setValidateCode();" /></li> <li>    <input name="forward" type="hidden" id="forward" value="http://127.0.0.1:8866/phpcms/member/"> <input name="dosubmit" type="submit" value="登 录" />    </li> </ul> <div id="login_b"></div> </div> <div id="login_r"> <a href="{:$smarty.const.BOOT_URL}/member/register"><img src="member/image/register.jpg" alt="" width="144" height="48" /></a> </div> <div class="clear"></div> <br/> </div> </form> {:include file="./foot.tpl"} <link href="common/style/ui.all.css" rel="stylesheet" type="text/css" /> <script language="javascript" type="text/javascript" src="common/js/jquery.js"></script> <script language="javascript" type="text/javascript" src="common/js/ui.core.js"></script> <script language="javascript" type="text/javascript" src="common/js/ui.draggable.js"></script> <script language="javascript" type="text/javascript" src="common/js/ui.dialog.js"></script> <script language="JavaScript" type="text/javascript" src="member/js/css.js"></script> <script language="javascript" type="text/javascript" src="common/js/jquery.post.js"></script> <script language="javascript" type="text/javascript" src="common/js/common.js"></script> <script language="javascript" type="text/javascript"> $(document).ready(function(){ $("form").post({ sendUrl:"{:$smarty.const.BOOT_URL}/member/login/check", trueJs:"redirect('{:$smarty.const.BOOT_URL}/member/');", falseJs:"setValidateCode();" }); }); function setValidateCode() { $("#validateImage").attr('src','{:$smarty.const.BOOT_URL}/common/validateCode/'+Math.ceil(Math.random()*1000)); } </script> </body> </html>
01cms
01cms/branches/2.0/template/member/login.tpl
Smarty
asf20
2,869
<div class="foot"> &copy; 2010 01CMS DEV TEAM. All rights reserved. Powered by <a target="_blank" href="http://www.01CMS.com/">01CMS</a> </div><!--/foot-->
01cms
01cms/branches/2.0/template/default/foot.tpl
Smarty
asf20
181
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{:$i->Load->var.siteName}</title> <link rel="stylesheet" href="{:$smarty.const.PUBLIC_DIR}/common/style/01cms.css" type="text/css" /> </head> <body> <div class="wrapper"> {:include file="./head.tpl"} <div class="index"> <div class="left"> <div class="flash"> <script language='javascript'> linkarr = new Array(); picarr = new Array(); textarr = new Array(); var swf_width=716; var swf_height=218; var files = ""; var links = ""; var texts = ""; var index = 0; //这里设置调用标记 {:counter start=0 print=false} {:archive size=5 flag='f'} index = {:counter}; linkarr[index] = "{:$item->url}"; picarr[index] = "{:$item->thumb}"; textarr[index] = '{:$item->title|@strip_tags}'; {:/archive} for(i=1;i<picarr.length;i++){ if(files=="") files = picarr[i]; else files += "|"+picarr[i]; } for(i=1;i<linkarr.length;i++){ if(links=="") links = linkarr[i]; else links += "|"+linkarr[i]; } for(i=1;i<textarr.length;i++){ if(texts=="") texts = textarr[i]; else texts += "|"+textarr[i]; } //不显示title //texts = ''; document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ swf_width +'" height="'+ swf_height +'">'); document.write('<param name="movie" value="{:$smarty.const.PUBLIC_DIR}/common/image/bcastr3.swf"><param name="quality" value="high">'); document.write('<param name="menu" value="false"><param name=wmode value="opaque">'); document.write('<param name="FlashVars" value="bcastr_file='+files+'&bcastr_link='+links+'&bcastr_title='+texts+'&bcastr_config=0xffffff|2|0xeeeeee|10|0xffffff|0xeeeeee|0x000033|2|0|1|_blank">'); document.write('<embed src="{:$smarty.const.PUBLIC_DIR}/common/image/bcastr3.swf" wmode="opaque" FlashVars="bcastr_config=0xffffff|2|0xeeeeee|10|0xffffff|0xeeeeee|0x000033|2|0|1|_blank&bcastr_file='+files+'&bcastr_link='+links+'&bcastr_title='+texts+'& menu="false" quality="high" width="'+ swf_width +'" height="'+ swf_height +'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'); document.write('</object>'); </script> </div> <!--/flash--> <dl class="picture"> <dt><em><a href="{:$category->staticUrl}">更多...</a></em>最新图文</dt> <dd> <ul> {:archive size=5 flag='p'} <li><img src="{:$item->thumb}" /><div><a href="{:$item->url}">{:$item->title}</a></div></li> {:/archive} </ul> <div class="clear"></div> </dd> </dl> {:block size=10 tpl="archiveBlock"} <dl> <dt><em><a href="{:$category->staticUrl}">更多...</a></em>{:$category->name}</dt> {:$archiveBlock} </dl> {:/block} <div class="blank5"></div> </div> <div class="panel"> <h3>推荐文章</h3> <ul> {:archive size=10} <li><a href="{:$item->staticUrl}">{:$item->title}</a></li> {:/archive} </ul> <h3>最新文章</h3> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h3>友情链接</h3> <ul> <li><a href="http://www.01cms.com" target="_blank">01CMS网站内容管理系统</a></li> </ul> </div> </div><!--/index--> {:include file="./foot.tpl"} </div><!--/wrapper--> </div> </body> </html>
01cms
01cms/branches/2.0/template/default/index.tpl
Smarty
asf20
4,235
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{:$i->data.name} - {:$i->Load->var.siteName}</title> <link rel="stylesheet" href="{:$smarty.const.PUBLIC_DIR}/common/style/01cms.css" type="text/css" /> </head> <body> <div class="wrapper"> {:include file="./head.tpl"} <div class="list"> <div class="left"> <div class="position"><strong>当前位置:</strong>{:categoryPosition id=$i->id}</div> {:foreach from=$i->lists item=item} <dl> <dt><em><a href="#" onclick="return false;">评论</a>(0)</em><a href="{:$item->url}">{:$item->title}</a> ({:$item->pubTime|date_format:"%y-%m-%d %H:%I"})</dt> <dd>{:$item->desc}</dd> </dl> {:/foreach} <dl>{:$i->pagesCode}</dl> <div class="blank5"></div> </div> <div class="right"> <h1>推荐文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>热门文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>最新文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>友情链接</h1> <ul> <li><a href="http://www.01mvc.com">01开发站</a></li> </ul> </div> </div><!--/mail--> {:include file="./foot.tpl"} </div><!--/wrapper--> </body> </html>
01cms
01cms/branches/2.0/template/default/articleList.tpl
Smarty
asf20
2,085
<div class="head"> <div class="info"> <a href="{:$smarty.const.ROOT_DIR}">本站首页</a> <a onclick="addFavor('{:$smarty.const.ROOT_DIR}', '{:$i->Load->var.siteName}');return false;" href="#">加入收藏</a> </div> <div class="logo"><a href="{:$smarty.const.ROOT_DIR}"><img src="{:$smarty.const.PUBLIC_DIR}/common/image/logo.gif" /></a></div> </div><!--/head--> <div class="nav"> <form id="search" action="{:$smarty.const.ROOT_DIR}/index.php/data/search" method="get">关键词:<input size="20" value="{:$i->keyWord}" name="k" /> <a href="#@" onclick="document.getElementById('search').submit();">搜索</a> </form> <div class="menu"> {:category} <a href="{:$item->url}">{:$item->name}</a> {:/category} </div> </div> <script language="javascript"> function addFavor(sURL, sTitle) { try { window.external.addFavorite(sURL, sTitle); } catch (e) { try { window.sidebar.addPanel(sTitle, sURL, ""); } catch (e) { alert("加入收藏到浏览器失败,请使用Ctrl+D进行添加"); } } } </script>
01cms
01cms/branches/2.0/template/default/head.tpl
Smarty
asf20
1,351
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{:$i->data.name} - {:$i->Load->var.siteName}</title> <link rel="stylesheet" href="{:$smarty.const.PUBLIC_DIR}/common/style/01cms.css" type="text/css" /> </head> <body> <div class="wrapper"> {:include file="./head.tpl"} <div class="list"> <div class="left"> <div class="position"><strong>当前位置:</strong>{:categoryPosition id=$i->id}</div> {:foreach from=$i->lists item=item} <dl> <dt><em><a href="#" onclick="return false;">评论</a>(0)</em><a href="{:$item->url}">{:$item->title}</a> ({:$item->pubTime|date_format:"%y-%m-%d %H:%I"})</dt> <dd>{:$item->desc}</dd> </dl> {:/foreach} <dl>{:$i->pagesCode}</dl> <div class="blank5"></div> </div> <div class="right"> <h1>推荐文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>热门文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>最新文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>友情链接</h1> <ul> <li><a href="http://www.01mvc.com">01开发站</a></li> </ul> </div> </div><!--/mail--> {:include file="./foot.tpl"} </div><!--/wrapper--> </body> </html>
01cms
01cms/branches/2.0/template/default/companyList.tpl
Smarty
asf20
2,085
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{:$i->data.name} - {:$i->Load->var.siteName}</title> <link rel="stylesheet" href="{:$smarty.const.PUBLIC_DIR}/common/style/01cms.css" type="text/css" /> </head> <body> <div class="wrapper"> {:include file="./head.tpl"} <div class="list"> <div class="left"> <div class="position"><strong>当前位置:</strong>{:categoryPosition id=$i->id}</div> {:foreach from=$i->lists item=item} <dl> <dt><em><a href="#" onclick="return false;">评论</a>(0)</em><a href="{:$item->url}">{:$item->title}</a> ({:$item->pubTime|date_format:"%y-%m-%d %H:%I"})</dt> <dd>{:$item->desc}</dd> </dl> {:/foreach} <dl>{:$i->pagesCode}</dl> <div class="blank5"></div> </div> <div class="right"> <h1>推荐文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>热门文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>最新文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>友情链接</h1> <ul> <li><a href="http://www.01mvc.com">01开发站</a></li> </ul> </div> </div><!--/mail--> {:include file="./foot.tpl"} </div><!--/wrapper--> </body> </html>
01cms
01cms/branches/2.0/template/default/pictureList.tpl
Smarty
asf20
2,085
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{:$i->show->title} - {:$i->Load->var.siteName}</title> <link rel="stylesheet" href="{:$smarty.const.PUBLIC_DIR}/common/style/01cms.css" type="text/css" /> </head> <body> <div class="wrapper"> {:include file="./head.tpl"} <div class="show"> <div class="left"> <div class="position"><strong>当前位置:</strong>{:categoryPosition id=$i->show->categoryId}</div> <h1>{:$i->show->title}</h1> <div class="info">{:$i->show->source} {:$i->show->pubTime|date_format:"%Y-%m-%d %H:%I"} {:$i->show->author}</div> <div class="desc">{:$i->show->desc}</div> <div class="content"> {:$i->show->content} <br /> {:$i->pagesCode} </div> <div class="blank5"></div> </div> <div class="middle"> <h1>推荐阅读:</h1> <ul> {:archive size=20} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> </div> <div class="right"> <h1>热门文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>最新文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> </div> </div><!--/main--> {:include file="./foot.tpl"} </div><!--/wrapper--> </body> </html>
01cms
01cms/branches/2.0/template/default/articleShow.tpl
Smarty
asf20
2,004
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{:$i->show->title} - {:$i->Load->var.siteName}</title> <link rel="stylesheet" href="{:$smarty.const.PUBLIC_DIR}/common/style/01cms.css" type="text/css" /> </head> <body> <div class="wrapper"> {:include file="./head.tpl"} <div class="show"> <div class="left"> <div class="position"><strong>当前位置:</strong>{:categoryPosition id=$i->show->categoryId}</div> <h1>{:$i->show->title}</h1> <div class="info">{:$i->show->source} {:$i->show->pubTime|date_format:"%Y-%m-%d %H:%I"} {:$i->show->author}</div> <div class="desc">{:$i->show->desc}</div> <div class="content"> {:$i->show->content} <br /> {:$i->pagesCode} </div> <div class="blank5"></div> </div> <div class="middle"> <h1>推荐阅读:</h1> <ul> {:archive size=20} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> </div> <div class="right"> <h1>热门文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>最新文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> </div> </div><!--/main--> {:include file="./foot.tpl"} </div><!--/wrapper--> </body> </html>
01cms
01cms/branches/2.0/template/default/companyShow.tpl
Smarty
asf20
2,004
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{:$i->data.name} - {:$i->Load->var.siteName}</title> <link rel="stylesheet" href="{:$smarty.const.PUBLIC_DIR}/common/style/01cms.css" type="text/css" /> </head> <body> <div class="wrapper"> {:include file="./head.tpl"} <div class="list"> <div class="left"> <div class="position"><strong>当前位置:</strong>{:categoryPosition id=$i->id} <strong>分类:</strong>{:category parentId = $i->id} <a href="{:$item->url}">{:$item->name}</a>{:/category}</div> {:foreach from=$i->lists item=item} <dl> <dt><em><a href="#" onclick="return false;">评论</a>(0)</em><a href="{:$item->url}">{:$item->title}</a> ({:$item->pubTime|date_format:"%y-%m-%d %H:%I"})</dt> <dd>{:$item->desc}</dd> </dl> {:/foreach} <dl>{:$i->pagesCode}</dl> <div class="blank5"></div> </div> <div class="right"> <h1>推荐文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>热门文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>最新文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>友情链接</h1> <ul> <li><a href="http://www.01mvc.com">01开发站</a></li> </ul> </div> </div><!--/mail--> {:include file="./foot.tpl"} </div><!--/wrapper--> </body> </html>
01cms
01cms/branches/2.0/template/default/categoryIndex.tpl
Smarty
asf20
2,196
{:foreach item=item from=$i->archiveBlock} <dd><em>[{:$item->pubTime|date_format:"%m-%d %H:%I"}]</em><a href="{:$item->url}">{:$item->title}</a></dd> {:/foreach}
01cms
01cms/branches/2.0/template/default/archiveBlock.tpl
Smarty
asf20
163
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>01开发站</title> <link rel="stylesheet" href="{:$smarty.const.PUBLIC_DIR}/common/style/01cms.css" type="text/css" /> <style> .result span{ color:#F60;} </style> </head> <body> <div class="wrapper"> {:include file="./head.tpl"} <div class="list"> <div class="left"> <h1>搜索:{:$i->keyWord}</h1> {:foreach from=$i->lists item=item} <dl class="result"> <dt><em><a href="#" onclick="return false;">评论</a>(0)</em><a href="{:$item->url}">{:$item->title}</a> ({:$item->pubTime|date_format:"%y-%m-%d %H:%I"})</dt> <dd>{:$item->desc}</dd> </dl> {:/foreach} <dl>{:$i->pagesCode}</dl> <div class="blank5"></div> </div> <div class="right"> <h1>推荐文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>热门文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>最新文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>友情链接</h1> <ul> <li><a href="http://www.01mvc.com">01开发站</a></li> </ul> </div> </div><!--/mail--> {:include file="./foot.tpl"} </div><!--/wrapper--> </body> </html>
01cms
01cms/branches/2.0/template/default/search.tpl
Smarty
asf20
2,039
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{:$i->show->title} - {:$i->Load->var.siteName}</title> <link rel="stylesheet" href="{:$smarty.const.PUBLIC_DIR}/common/style/01cms.css" type="text/css" /> </head> <body> <div class="wrapper"> {:include file="./head.tpl"} <div class="show"> <div class="left"> <div class="position"><strong>当前位置:</strong>{:categoryPosition id=$i->show->categoryId}</div> <h1>{:$i->show->title}</h1> <div class="info">{:$i->show->source} {:$i->show->pubTime|date_format:"%Y-%m-%d %H:%I"} {:$i->show->author}</div> <div class="desc">{:$i->show->desc}</div> <div class="content"> {:$i->show->content} <br /> {:$i->pagesCode} </div> <div class="blank5"></div> </div> <div class="middle"> <h1>推荐阅读:</h1> <ul> {:archive size=20} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> </div> <div class="right"> <h1>热门文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> <h1>最新文章</h1> <ul> {:archive size=10} <li><a href="{:$item->url}">{:$item->title}</a></li> {:/archive} </ul> </div> </div><!--/main--> {:include file="./foot.tpl"} </div><!--/wrapper--> </body> </html>
01cms
01cms/branches/2.0/template/default/pictureShow.tpl
Smarty
asf20
2,004
<?php /** * 全局配置文件 * * secret:安装时自动生成的加密字符串,请勿修改 * urlSuffix:URL伪后缀,用于URL重写时去掉入口文件名 */ return array ( 'secret' => 'f0767113f405339ff7c22055c7bd000a', 'urlSuffix' => '', 'mysql' => array ( 'hostname' => 'localhost', 'username' => 'root', 'password' => 'feawadsx', 'database' => '01cms', 'prefix' => '01cms_', 'pconnect' => false, 'charset' => 'utf8', ), );
01cms
01cms/branches/2.0/01mvc/config/config.php
PHP
asf20
485
<?php return array ( 'siteName' => '01CMS 网站内容管理系统', 'pageDelimiter' => '<div style="page-break-after: always;"><span style="display: none;">01cms</span></div>', 'pagesContentChannel' => 'article', 'pageSize' => '20', 'htmlSaveDir' => '/html', 'homepageTemplateName' => 'index.tpl', 'homepageFileName' => 'index.html', 'publicAppPath' => '/www', 'style' => 'default', );
01cms
01cms/branches/2.0/01mvc/config/var.php
PHP
asf20
404
<?php return array ( 'uploadPath' => 'Y/md', 'allowedTypes' => 'jpg|png|gif|rar|zip|doc|txt', 'maxSize' => '2048', 'createThumb' => '1', 'thumbWidth' => '200', 'thumbHeight' => '150', 'thumbPadColor' => '#FFFFFF', 'thumbMarker' => '_thumb', 'width' => '1024', 'height' => '768', 'wmText' => 'www.01cms.com', 'wmType' => 'overlay', 'wmFontSize' => '16', 'wmFontPath' => 'vrinda.ttf', 'wmFontColor' => '#FFFFFF', 'wmShadowColor' => '#333333', 'wmShadowDistance' => '2', 'wmVrtAlignment' => 'B', 'wmHorAlignment' => 'R', 'wmOpacity' => '60', 'wmPadding' => '-5', 'wmOverlayPath' => 'logo.gif', 'wmHorOffset' => '0', 'wmVrtOffset' => '0', );
01cms
01cms/branches/2.0/01mvc/data/uploadSetting.php
PHP
asf20
685
<?php return array( 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'), 'bin' => 'application/macbinary', 'dms' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'exe' => 'application/octet-stream', 'class' => 'application/octet-stream', 'psd' => 'application/x-photoshop', 'so' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => array('application/pdf', 'application/x-download'), 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'), 'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'), 'wbxml' => 'application/wbxml', 'wmlc' => 'application/wmlc', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'php' => 'application/x-httpd-php', 'php4' => 'application/x-httpd-php', 'php3' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source', 'js' => 'application/x-javascript', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', 'tgz' => 'application/x-tar', 'xhtml' => 'application/xhtml+xml', 'xht' => 'application/xhtml+xml', 'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'), 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mpga' => 'audio/mpeg', 'mp2' => 'audio/mpeg', 'mp3' => array('audio/mpeg', 'audio/mpg'), 'aif' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'rv' => 'video/vnd.rn-realvideo', 'wav' => 'audio/x-wav', 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpeg' => array('image/jpeg', 'image/pjpeg'), 'jpg' => array('image/jpeg', 'image/pjpeg'), 'jpe' => array('image/jpeg', 'image/pjpeg'), 'png' => array('image/png', 'image/x-png'), 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'css' => 'text/css', 'html' => 'text/html', 'htm' => 'text/html', 'shtml' => 'text/html', 'txt' => 'text/plain', 'text' => 'text/plain', 'log' => array('text/plain', 'text/x-log'), 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'xml' => 'text/xml', 'xsl' => 'text/xml', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie', 'doc' => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'word' => array('application/msword', 'application/octet-stream'), 'xl' => 'application/excel', 'eml' => 'message/rfc822' );
01cms
01cms/branches/2.0/01mvc/data/mime.php
PHP
asf20
3,812
<?php return array ( 1 => array ( 'name' => '经典童话', 'isHidden' => '0', 'type' => '2', 'alias' => 'jingdiantonghua', 'channelId' => '0', 'pageSize' => '20', 'categoryTemplateName' => 'categoryIndex.tpl', 'archiveTemplateName' => '', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '4,3,2', 'allSonIds' => '4,3,2', ), 2 => array ( 'name' => '安徒生童话', 'isHidden' => '0', 'type' => '1', 'alias' => 'antushengtonghua', 'channelId' => '1', 'pageSize' => '20', 'categoryTemplateName' => 'articleList.tpl', 'archiveTemplateName' => 'articleShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '', 'allSonIds' => '', ), 3 => array ( 'name' => '格林童话', 'isHidden' => '0', 'type' => '1', 'alias' => 'gelintonghua', 'channelId' => '1', 'pageSize' => '20', 'categoryTemplateName' => 'articleList.tpl', 'archiveTemplateName' => 'articleShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '', 'allSonIds' => '', ), 4 => array ( 'name' => '寓言故事', 'isHidden' => '0', 'type' => '1', 'alias' => 'yuyangushi', 'channelId' => '1', 'pageSize' => '20', 'categoryTemplateName' => 'articleList.tpl', 'archiveTemplateName' => 'articleShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '', 'allSonIds' => '', ), 5 => array ( 'name' => '哲理故事', 'isHidden' => '0', 'type' => '1', 'alias' => 'zheligushi', 'channelId' => '1', 'pageSize' => '20', 'categoryTemplateName' => 'articleList.tpl', 'archiveTemplateName' => 'articleShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '', 'allSonIds' => '', ), 6 => array ( 'name' => '禅理故事', 'isHidden' => '0', 'type' => '1', 'alias' => 'chanligushi', 'channelId' => '1', 'pageSize' => '20', 'categoryTemplateName' => 'articleList.tpl', 'archiveTemplateName' => 'articleShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '', 'allSonIds' => '', ), 7 => array ( 'name' => '成败故事', 'isHidden' => '0', 'type' => '1', 'alias' => 'chengbaigushi', 'channelId' => '1', 'pageSize' => '20', 'categoryTemplateName' => 'articleList.tpl', 'archiveTemplateName' => 'articleShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '', 'allSonIds' => '', ), 8 => array ( 'name' => '图片欣赏', 'isHidden' => '0', 'type' => '2', 'alias' => 'tupianxinshang', 'channelId' => '2', 'pageSize' => '20', 'categoryTemplateName' => 'categoryIndex.tpl', 'archiveTemplateName' => 'pictureShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '12', 'allSonIds' => '12,9,10', ), 9 => array ( 'name' => '非主流美女', 'isHidden' => '0', 'type' => '1', 'alias' => 'feizhuliumeinv', 'channelId' => '2', 'pageSize' => '20', 'categoryTemplateName' => 'pictureList.tpl', 'archiveTemplateName' => 'pictureShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '', 'allSonIds' => '', ), 10 => array ( 'name' => '非主流签名', 'isHidden' => '0', 'type' => '1', 'alias' => 'feizhuliuqianming', 'channelId' => '2', 'pageSize' => '20', 'categoryTemplateName' => 'pictureList.tpl', 'archiveTemplateName' => 'pictureShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '', 'allSonIds' => '', ), 11 => array ( 'name' => '01CMS官方', 'isHidden' => '0', 'type' => '0', 'alias' => '01CMSguanfang', 'channelId' => '0', 'pageSize' => '20', 'categoryTemplateName' => '', 'archiveTemplateName' => '', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => 'http://www.01cms.com', 'sonIds' => '', 'allSonIds' => '', ), 12 => array ( 'name' => '非主流', 'isHidden' => '0', 'type' => '2', 'alias' => 'feizhuliu', 'channelId' => '0', 'pageSize' => '20', 'categoryTemplateName' => 'categoryIndex.tpl', 'archiveTemplateName' => '', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '9,10', 'allSonIds' => '9,10', ), 13 => array ( 'name' => '企业名录', 'isHidden' => '0', 'type' => '1', 'alias' => 'qiyeminglu', 'channelId' => '3', 'pageSize' => '20', 'categoryTemplateName' => 'companyList.tpl', 'archiveTemplateName' => 'companyShow.tpl', 'archiveUrl' => '/html/[alias]/%Y/%m%d/[id].html', 'link' => '', 'sonIds' => '', 'allSonIds' => '', ), 'ids' => array ( 'jingdiantonghua' => '1', 'antushengtonghua' => '2', 'gelintonghua' => '3', 'yuyangushi' => '4', 'zheligushi' => '5', 'chanligushi' => '6', 'chengbaigushi' => '7', 'tupianxinshang' => '8', 'feizhuliumeinv' => '9', 'feizhuliuqianming' => '10', '01CMSguanfang' => '11', 'feizhuliu' => '12', 'qiyeminglu' => '13', ), );
01cms
01cms/branches/2.0/01mvc/data/archiveCategory.php
PHP
asf20
5,454
<?php return array ( 1 => array ( 'name' => '文章', 'tableId' => 'article', 'fieldList' => 'content|文章内容不能为空', 'categoryIds' => '2,3,4,5,6,7', ), 2 => array ( 'name' => '图集', 'tableId' => 'picture', 'fieldList' => 'content|图片内容不能为空', 'categoryIds' => '8,9,10', ), 3 => array ( 'name' => '企业', 'tableId' => 'company', 'fieldList' => 'contact|联系人不能为空,business,address,tel,homepage', 'categoryIds' => '13', ), );
01cms
01cms/branches/2.0/01mvc/data/archiveChannel.php
PHP
asf20
534
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>01CMS 提示信息</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <style> body { font-family: Verdana; font-size:13px; } h1 { border-bottom:1px solid #ccc; padding:0 0 5px 0; font-size:18px; margin:0 0 5px 0; } a { text-decoration:none; color:#666; font-weight:bold; padding:0 3px; } a:hover { color:#FF6600; } p { padding:0; margin:0; } .wrapper { padding:10px; margin:5px auto; color:#666; background:#F6F6F6; border:1px solid #ccc; width:600px; } .message { padding:10px; line-height:150%; background:#fff; border:1px solid #eee; color:#000;} .action { padding:0; margin:15px 0 8px 0; } </style> </head> <body> <div class="wrapper"> <h1>01CMS 提示信息</h1> <p class="message"><?php echo $message;?></p> <p class="action"> [<a href="<?php if(isset(Base::i()->backUrl)){echo Base::i()->backUrl;}else{echo 'javascript:history.back()';}?>">返回</a>] [<a href="<?php echo getCurUrl ();?>">重试</a>] [<a href="http://www.01cms.com">求助</a>]</p> </div> </body> </html>
01cms
01cms/branches/2.0/01mvc/view/info.php
PHP
asf20
1,204
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>01CMS ERROR</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <style> body { font-family: Verdana; font-size:13px; } h1 { border-bottom:1px solid #ddd; padding:8px 0; font-size:18px; margin:0 0 10px 0; } a { text-decoration:none; color:#000; font-weight:bold; padding:0 3px; } a:hover { color:#FF6600; } p { padding:0; margin:0; } .wrapper { padding:10px; margin:5px; color:#666; background:#FCFCFC; border:1px solid #ddd; } .message { padding:10px; line-height:150%; background:#ffd; border:1px solid #eee; color:#999;} .action { padding:0; margin:15px 0 8px 0; } .error{ color:#000; font-weight:bold;} </style> </head> <body> <div class="wrapper"> <h1>01CMS ERROR</h1> <p class="message"><?php echo $message;?></p> <p class="action"> [<a href="<?php echo($_SERVER['PHP_SELF'])?>">重试</a>] [<a href="javascript:history.back()">返回</a>] [<a href="http://www.01cms.com">发送错误</a>] 到官方网站或登陆 [<a href="http://www.01cms.com">01CMS</a>] 求助中心寻求解决方案</p> </div> </body> </html>
01cms
01cms/branches/2.0/01mvc/view/error.php
PHP
asf20
1,245
<?php /** * 系统引导文件 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ if (! defined('SYS_PATH')) { exit('SYS_PATH ERROR'); } try { require (SYS_PATH . '/lib/Load.php'); $Load = new Load(); require (SYS_PATH . '/common.php'); require (SYS_PATH . '/lib/Uri.php'); require (SYS_PATH . '/lib/Base.php'); require (SYS_PATH . '/lib/Controller.php'); $Uri = lib('Uri'); $c = $Uri->getClassName(); $m = $Uri->getMethodName(); $p = $Uri->getParam(); $controllerName = $c . 'Controller'; if (! file_exists(APP_PATH . '/controller/' . $controllerName . '.php')) { throw new Exception('您访问的页面不存在'); } else { require (APP_PATH . '/controller/' . $controllerName . '.php'); } if (class_exists($controllerName, FALSE)) { $Controller = new $controllerName(); if (method_exists($Controller, $m) && ! empty($m)) { call_user_func_array(array($Controller, $m), $p); } else { throw new Exception('您访问的页面不存在'); } } else { throw new Exception('您访问的页面不存在'); } } catch (Exception $e) { $message = '<span class="error">' . $e->getMessage() . '</span>'; include SYS_PATH . '/view/error.php'; } /* End of file /01CMS/01mvc/boot.php */
01cms
01cms/branches/2.0/01mvc/boot.php
PHP
asf20
1,590
<?php /** * 全局函数和设置 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ //设定编码 header('Content-Type: text/html; charset=utf-8'); //设置时区 if (function_exists('date_default_timezone_set')) { date_default_timezone_set('Asia/Shanghai'); } //定义时间常量 define('TIME', time()); if (! function_exists('date_default_timezone_set')) { function json_encode ($data) { return lib('Services_JSON')->encode($data); } } if (! defined('DIRECTORY_SEPARATOR')) { define('DIRECTORY_SEPARATOR', strtoupper(substr(PHP_OS, 0, 3) == 'WIN') ? '\\' : '/'); } /** * 自动加载[类文件] * * @param string $className * @return void */ function __autoload ($className) { $type = (strpos($className, 'Model') > 0) ? 'model' : 'lib'; if (file_exists(APP_PATH . '/' . $type . '/' . $className . '.php')) { require_once (APP_PATH . '/' . $type . '/' . $className . '.php'); } else if (file_exists(SYS_PATH . '/' . $type . '/' . $className . '.php')) { require_once (SYS_PATH . '/' . $type . '/' . $className . '.php'); } else if (file_exists(APP_PATH . '/' . $type . '/' . $className . '/' . $className . '.php')) { require_once (APP_PATH . '/' . $type . '/' . $className . '/' . $className . '.php'); } else if (file_exists(SYS_PATH . '/' . $type . '/' . $className . '/' . $className . '.php')) { require_once (SYS_PATH . '/' . $type . '/' . $className . '/' . $className . '.php'); } else { throw new Exception("Class '{$className}' not found!"); } } /** * 加载类库 * * @param string $libName * @param mix $param * @return object */ function lib ($libName, $param = NULL) { return $GLOBALS['Load']->_class($libName, $param); } /** * 加载模型 * * @param string $libName * @param mix $param * @return object */ function model ($modelName, $param = NULL) { return $GLOBALS['Load']->_class($modelName . 'Model', $param); } /** * 加载数据 * * @param string $libName * @param mix $param * @return object */ function data ($fileName) { return $GLOBALS['Load']->_file($fileName, 'data'); } /** * 加载配置文件 * * @param string $libName * @param mix $param * @return object */ function config ($fileName) { return $GLOBALS['Load']->_file($fileName, 'config'); } /** * 输出错误并中止程序运行 * * @param string $message 错误提示信息 * @return void */ function showError ($message = '') { if ($message == '404') { $message = '您访问的页面不存在!'; } $message = '<span class="error">' . $message . '</span>'; include SYS_PATH . '/view/error.php'; exit(); } /** * 输出提示信息 * * @param string $message 提示信息 * @return void */ function showInfo ($message = '') { include SYS_PATH . '/view/info.php'; exit(); } /** * postResponse * * @param string $message * @param string $goUrl * @param string $stayTime * @param string $javascript * @return void */ function responseToParent ($message, $goUrl = '', $stayTime = 3, $javascript = FALSE) { $info = json_encode(array('message'=>$message, 'goUrl'=>$goUrl, 'stayTime'=>$stayTime, 'javascript'=>$javascript)); echo '<script language="javascript" type="text/javascript">window.parent.postResponse(' . $info . ');</script>'; exit(); } /** * response * * @param string $message * @param string $success * @param string $javascript * @return void */ function response ($message, $success = FALSE, $javascript = FALSE) { header('Cache-Control:no-cache, must-revalidate'); echo json_encode(array('message'=>$message, 'success'=>$success, 'javascript'=>$javascript)); exit(); } /** * 对引号添加或去除反斜杠 * * @param string $svar * @param string $type (add | slash) * @param string $force * @return void */ function slashQuotes (&$svar, $type = 'add', $force = false) { if (! get_magic_quotes_gpc() || $force) { if (is_array($svar)) { foreach ($svar as $_k => $_v) $svar[$_k] = slashQuotes($_v, $type, $force); } else { $svar = ($type == 'add') ? addslashes($svar) : stripslashes($svar); } } return $svar; } /** * 跳转 * * @param string $url * @return void */ function redirect ($url) { if (strpos($url, 'http://') !== 0) { $url = BOOT_URL . '/' . $url; } header('location:' . $url); } /** * 获取客户端IP * * @return string */ function getIp () { if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) { $ip = getenv('HTTP_CLIENT_IP'); } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) { $ip = getenv('REMOTE_ADDR'); } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) { $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } /** * 获取加密字符串 * * @param string $var * @return string */ function encrypt ($var) { return md5(Base::i()->Load->config['secret'] . $var); } /** * 新建文件夹 * * @param string $folder * @param int $mode (0764) * @return bool */ function makeDirs ($folder, $mode = 0764) { if (file_exists($folder)) { return false; } $mkfolder = (substr($folder, 0, 1) == "/") ? '/' : ''; $folder = explode("/", $folder); for ($i = 0; isset($folder[$i]); $i ++) { $parentFolder = $mkfolder; $mkfolder .= empty($folder[$i]) ? '' : $folder[$i] . "/"; if (is_writable($parentFolder)) { if (! file_exists($mkfolder) && $i > 1) { mkdir($mkfolder, $mode); } } } return TRUE; } /** * 检测是否非空 * * @param string $var * @return bool */ function notEmpty ($var) { return (! empty($var)); } /** * 清空目录 * * @param string $dir * @return string */ function clearDirs ($dir) { $dirHandle = opendir($dir); $msg = ''; while ($fileName = readdir($dirHandle)) { if ($fileName != "." && $fileName != "..") { if (is_dir("$dir/$fileName")) { clearDirs($dir . "/" . $fileName); if (@rmdir("$dir/$fileName")) { $msg .= "成功删除:"; } else { $msg .= "删除失败:"; } $msg .= " -- <strong>$dir/$fileName</strong>"; $msg .= "<br />"; } else { if (@unlink("$dir/$fileName")) { $msg .= "成功删除:"; } else { $msg .= "删除失败:"; } $msg .= " -- $dir/$fileName"; $msg .= "<br />"; } } } closedir($dirHandle); return $msg; } /** * 获取当前URL * * @return string */ function getCurUrl () { if (! empty($_SERVER["REQUEST_URI"])) { return $_SERVER["REQUEST_URI"]; } else { $scriptName = $_SERVER["PHP_SELF"]; if (empty($_SERVER["QUERY_STRING"])) { return $scriptName; } else { return $scriptName . "?" . $_SERVER["QUERY_STRING"]; } } } /** * 中文截取(UTF-8) * * @param string $str * @param int $start * @param int $length * @return string */ function cnSubstr ($str, $start, $length) { if (function_exists('mb_substr')) { return mb_substr($str, $start, $length, 'UTF-8'); } $arr = array(); preg_match_all("/./u", $str, $arr); return implode('', array_slice($arr[0], $start, $length)); } /** * 获取缩略图 * * @param string $url * @return string */ function getThumb ($url) { if(empty($url)) { return PUBLIC_DIR . '/common/image/no_thumb.gif'; } $setting = data('uploadSetting'); $pos = strrpos($url, '.'); return substr($url, 0, $pos) . $setting['thumbMarker'] . substr($url, $pos); } //END
01cms
01cms/branches/2.0/01mvc/common.php
PHP
asf20
9,105
<?php /** * 栏目列表 * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_block_category ($params, $content, $smarty, &$repeat) { static $category = array(); if (is_null($content)) { $parentId = isset($params['parentId']) ? $params['parentId'] : 0; $category = model('Category')->getChildren($parentId, 0, 0, 1, '', '', 'isHidden = 0'); } if ($o = current($category)) { if ($o->type > 0) { $o->activeUrl = BOOT_URL . '/data/category/' . $o->id; $o->staticUrl = ROOT_DIR . Base::i()->Load->var['htmlSaveDir'] . '/' . $o->alias; switch ($o->visit) { case 1: { $o->url = $o->staticUrl; break; } case 2: { $o->url = $o->activeUrl; break; } default: { $o->url = defined('staticHtml') ? $o->staticUrl : $o->activeUrl; } } } else { $o->activeUrl = $o->staticUrl = $o->url = $o->link; } $smarty->assign('item', $o); next($category); $repeat = true; } else { $repeat = false; } return $content; }
01cms
01cms/branches/2.0/01mvc/plugin/block.category.php
PHP
asf20
1,565
<?php /** * 列出所有栏目的文档 * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_block_block ($params, $content, $smarty, &$repeat) { static $category = array(); if (is_null($content)) { $parentId = isset($params['parentId']) ? $params['parentId'] : 0; $category = model('Category')->getChildren ($parentId, 0, 1); } if ($o = current($category)) { if ($o->type != 0) { $o->activeUrl = BOOT_URL . '/data/category/' . $o->id; $o->staticUrl = Base::i()->Load->var['htmlSaveDir'] . '/' . $o->alias; $o->url = defined('staticHtml') ? $o->staticUrl : $o->activeUrl; $smarty->assign('category', $o); $params['categoryId'] = $o->id; if(empty($params['tpl'])){ $params['tpl'] = 'archiveBlock'; } $data = model('Archive')->getArchives($params); Base::i()->archiveBlock = model('Archive')->setArchiveFlag($data); $contentBlock = $smarty->fetch($params['tpl'].'.tpl'); $smarty->assign('archiveBlock', $contentBlock); } next($category); $repeat = true; } else { $repeat = false; } return $content; }
01cms
01cms/branches/2.0/01mvc/plugin/block.block.php
PHP
asf20
1,468
<?php /** * 调用文档 * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_block_archive ($params, $content, $smarty, &$repeat) { static $data = array(); if (is_null($content)) { $Model = model('Archive'); $data = $Model->getArchives($params); $data = $Model->setArchiveFlag($data); } if ($o = current($data)) { $smarty->assign('item', $o); next($data); $repeat = true; } else { $repeat = false; } return $content; }
01cms
01cms/branches/2.0/01mvc/plugin/block.archive.php
PHP
asf20
679
<?php /** * 打印HTML * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_modifier_printHtml ($string) { return htmlspecialchars(stripslashes($string)); }
01cms
01cms/branches/2.0/01mvc/plugin/modifier.printHtml.php
PHP
asf20
286
<?php /** * 当前位置 * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_function_categoryPosition ($params) { if (! isset($params['isLink'])) { $params['isLink'] = 1; } if (! isset($params['sign'])) { $params['sign'] = ' » '; } $Category = model('Category'); $Category->getParent($params['id']); $parent = $Category->parentCategory; $string = ''; foreach ($parent as $o) { if ($params['isLink']) { $o->activeUrl = BOOT_URL . '/data/category/' . $o->id; $o->staticUrl = ROOT_DIR . Base::i()->Load->var['htmlSaveDir'] . '/' . $o->alias; switch ($o->visit) { case 1: { $o->url = $o->staticUrl; } case 2: { $o->url = $o->activeUrl; } default: { $o->url = defined('staticHtml') ? $o->staticUrl : $o->activeUrl; } } $o->name = "<a href=\"{$o->url}\">{$o->name}</a>"; } if (empty($string)) { $string = $o->name; } else { $string = $o->name . $params['sign'] . $string; } } return $string; }
01cms
01cms/branches/2.0/01mvc/plugin/function.categoryPosition.php
PHP
asf20
1,552
<?php /** * 获取缩略图地址 * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_modifier_thumb ($url) { return getThumb($url); }
01cms
01cms/branches/2.0/01mvc/plugin/modifier.thumb.php
PHP
asf20
265
<?php /** * 输出应用于title里的HTML * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_modifier_tipHtml ($string) { return nl2br(str_replace('"','\'',$string)); }
01cms
01cms/branches/2.0/01mvc/plugin/modifier.tipHtml.php
PHP
asf20
299
<?php /** * 栏目别名 * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_modifier_alias ($id) { $category = Base::i()->Load->data('category'); return $category[$id]['alias']; }
01cms
01cms/branches/2.0/01mvc/plugin/modifier.alias.php
PHP
asf20
313
<?php /** * 转换ID * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_modifier_translateId ($id,$var) { if (isset(Base::i()->{$var}[$id])) { return Base::i()->{$var}[$id]; } return $var; }
01cms
01cms/branches/2.0/01mvc/plugin/modifier.translateId.php
PHP
asf20
352
<?php /** * 当前位置 * * @package 01CMS * @subpackage plugin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ function smarty_function_categoryInfo ($params) { $Category = model('Category', $params['id']); if ($Category->type > 0) { $Category->activeUrl = BOOT_URL . '/category/' . $params['id']; $Category->staticUrl = ROOT_DIR . Base::i()->Load->var['htmlSaveDir'] . '/' . $Category->alias; switch ($Category->visit) { case 1: { $Category->url = $Category->staticUrl; break; } case 2: { $Category->url = $Category->activeUrl; break; } default: { $Category->url = defined('staticHtml') ? $Category->staticUrl : $Category->activeUrl; } } } else { $Category->url = $Category->link; } return $Category->$params['field']; }
01cms
01cms/branches/2.0/01mvc/plugin/function.categoryInfo.php
PHP
asf20
1,105
<?php /** * 加载数据类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Load { public $config = array(); public $var = array(); private $object = array(); private $conf = array(); private $data = array(); private $error = ''; private $Smarty; private $Base; private $templateName; function __construct () { $this->config = $this->_file('config', 'config'); $this->var = include_once (SYS_PATH . '/config/var.php'); if (file_exists(APP_PATH . '/config/var.php')) { $var = include_once (APP_PATH . '/config/var.php'); $this->var = array_merge($this->var, $var); unset($var); } } /** * 加载类库 * * @param string $libName * @param mix $param * @return object */ function lib ($libName, $param = NULL) { return $this->_class($libName, $param); } /** * 加载模型 * * @param string $libName * @param mix $param * @return object */ function model ($modelName, $param = NULL) { return $this->_class($modelName . 'Model', $param); } /** * 加载数据 * * @param string $libName * @param mix $param * @return object */ function data ($fileName) { return $this->_file($fileName, 'data'); } /** * 加载配置文件 * * @param string $libName * @param mix $param * @return object */ function config ($fileName) { return $this->_file($fileName, 'config'); } /** * 加载对象 * * @param string $fileName * @param string $param * @return object * @access public */ public function &_class ($className, $param = NULL) { $paramId = (is_string($param) || is_int($param)) ? $param : ''; $classId = $className . $paramId; if (isset($this->object[$classId])) { return $this->object[$classId]; } $this->object[$classId] = new $className($param); return $this->object[$classId]; } /** * 加载数据文件 * * @param string $fileName * @param string $type [data|config] * @return array * @access public */ public function &_file ($fileName, $type = 'data') { if (strpos($fileName, '/') !== FALSE) { $fileNameArr = explode('/', $fileName); $varName = $type . ucfirst($fileNameArr[0]) . ucfirst($fileNameArr[1]); } else { $varName = $type . $fileName; } if (isset($this->data[$varName])) { return $this->data[$varName]; } if (file_exists(APP_PATH . "/{$type}/" . $fileName . '.php')) { $this->data[$varName] = include_once (APP_PATH . "/{$type}/" . $fileName . '.php'); } else if (file_exists(SYS_PATH . "/{$type}/" . $fileName . '.php')) { $this->data[$varName] = include_once (SYS_PATH . "/{$type}/" . $fileName . '.php'); } else { return FALSE; } return $this->data[$varName]; } /** * 加载Smarty * * @param string $templateSuffix * @param int $lifeTime * @return void * @access public */ public function smarty ($templateSuffix = '', $lifeTime = -1) { $this->Base = & Base::i(); $this->templateName = $this->Base->m . ucfirst($templateSuffix) . '.tpl'; $tplPath = isset($this->Base->templateDir) ? $this->Base->templateDir : APP_PATH . '/view/' . $this->Base->c; $this->Smarty = $this->_class('Smarty'); //$Smarty->debugging = true; //$this->Smarty->config_dir = ''; //$this->Smarty->use_sub_dirs = true; $this->Smarty->template_dir = $tplPath; $compile_dir = APP_PATH . '/data/compile/' . $this->Base->c . '/' . $this->Base->m; if (! file_exists($compile_dir)) { makeDirs($compile_dir); } if (empty($lifeTime)) { $caching = FALSE; } else { $caching = 1; $cache_dir = APP_PATH . '/data/smarty/cache/' . $this->Base->c . '/' . $this->Base->m; if (! file_exists($cache_dir)) { makeDirs($cache_dir); } $this->Smarty->cache_dir = $cache_dir; } $this->Smarty->compile_dir = $compile_dir; $this->Smarty->compile_id = isset($this->Base->compileId) ? $this->Base->compileId : ''; $this->Smarty->plugins_dir = array(APP_PATH . '/plugin', SYS_PATH . '/plugin', SYS_PATH . '/lib/Smarty/plugins'); $this->Smarty->caching = $caching; if ($caching) { $this->Smarty->cache_lifetime = $lifeTime; if ($this->Smarty->is_cached($this->templateName)) { $this->Smarty->display($this->templateName); exit(); } } } /** * 加载视图 * * @param string $type * @param string $templateSuffix * @return void * @access public */ public function view ($type = '', $templateSuffix = '') { if ('smarty' == strtolower($type)) { if (! is_object($this->Smarty)) { $this->smarty($templateSuffix, 0); } $this->Smarty->left_delimiter = '{:'; $this->Smarty->assign_by_ref('i', Base::i()); $this->Smarty->display($this->templateName); } else if ('php' == strtolower($type) || empty($type)) { global $c, $m; $tplPath = APP_PATH . '/view/' . $c; if (! file_exists($tplPath . '/' . $m . ucfirst($templateSuffix) . '.tpl')) { trigger_error('模板文件 ' . $tplPath . '/' . $m . ucfirst($templateSuffix) . '.tpl 不存在', E_USER_ERROR); } include ($tplPath . '/' . $m . ucfirst($templateSuffix) . '.tpl'); } } /** * 获取POST变量 * * @param string $keys * @param string $type * @return mix * @access public */ public function post ($keys, $type = '') { $data = $this->processData($_POST, $keys); return ($type == 'one') ? $data[$keys] : $data; } /** * 获取GET变量 * * @param string $keys * @param string $type * @return mix * @access public */ public function get ($keys, $type = '') { $data = $this->processData($_GET, $keys); return ($type == 'one') ? $data[$keys] : $data; } /** * 获取查询变量 * * @param string $varString * @param string $type * @return mix * @access public */ public function query ($varString, $type = '') { if (! empty($_SERVER['QUERY_STRING'])) { parse_str($_SERVER['QUERY_STRING']); $varNames = explode(',', $varString); $data = array(); foreach ($varNames as $varName) { $data[$varName] = isset($$varName) ? slashQuotes($$varName, 'add', TRUE) : ''; } return ($type == 'one') ? $data[$varString] : $data; } return FALSE; } /** * 获取错误信息 * * @return string * @access public */ public function getError () { return $this->error; } private function processData ($array, $keys) { $keys = explode(',', $keys); $return = array(); foreach ($keys as $key) { $key = explode('|', $key); $field = $key[0]; if (isset($array[$field])) { $curValue = slashQuotes($array[$field]); if (is_array($curValue)) { foreach ($curValue as $subCurValue) { if (empty($subCurValue)) { $this->error = $key[1]; return FALSE; } } } else if (isset($key[1]) && empty($curValue)) { $this->error = $key[1]; return FALSE; } $return[$field] = $curValue; } else { if (isset($key[1])) { $this->error = $key[1]; return FALSE; } $return[$field] = NULL; } } return $return; } } // END
01cms
01cms/branches/2.0/01mvc/lib/Load.php
PHP
asf20
9,492
<?php /** * 静态分页类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class StaticPages { public $baseUrl = ''; public $firstFileName = ''; public $fileId = ''; public $fileExt = '.html'; public $totalPages = ''; public $pageSize = ''; public $numLinks = 5; public $curPage = 1; public $firstLink = '&lsaquo; 首页'; public $nextLink = '下一页'; public $prevLink = '上一页'; public $lastLink = '尾页 &rsaquo;'; public $fullTagOpen = ''; public $fullTagClose = ''; public $firstTagOpen = ''; public $firstTagClose = '&nbsp;'; public $lastTagOpen = '&nbsp;'; public $lastTagClose = ''; public $curTagOpen = '&nbsp;<strong>'; public $curTagClose = '</strong>'; public $nextTagOpen = '&nbsp;'; public $nextTagClose = '&nbsp;'; public $prevTagOpen = '&nbsp;'; public $prevTagClose = ''; public $numTagOpen = '&nbsp;'; public $numTagClose = ''; public $Base; function __construct () { $this->Base = & Base::i(); } function initialize ($params = array()) { if (count($params) > 0) { foreach ($params as $key => $val) { if (isset($this->$key)) { $this->$key = $val; } } } } function createLinks ($params) { if (count($params) > 0) { $this->initialize($params); } if (! ($this->totalPages > 0)) { $this->Base->pagesCode = '<span>没有记录</span>'; return ''; } if ($this->totalPages == 1) { $this->Base->pagesCode = '<span>共1页</span>'; return ''; } $this->curPage = (int) $this->curPage; $this->numLinks = (int) $this->numLinks; if (! is_numeric($this->curPage)) { $this->curPage = 1; } if ($this->curPage > $this->totalPages) { $this->curPage = $this->totalPages; } $start = (($this->curPage - $this->numLinks) > 0) ? $this->curPage - ($this->numLinks - 1) : 1; $end = (($this->curPage + $this->numLinks) < $this->totalPages) ? $this->curPage + $this->numLinks : $this->totalPages; $output = ''; if ($this->curPage > $this->numLinks) { $output .= $this->firstTagOpen . '<a href="' . $this->baseUrl . '/' . $this->firstFileName . '">' . $this->firstLink . '</a>' . $this->firstTagClose; } if ($this->curPage > 2) { $output .= $this->prevTagOpen . '<a href="' . $this->baseUrl . '/' . $this->fileId . ($this->curPage - 1) . $this->fileExt . '">' . $this->prevLink . '</a>' . $this->prevTagClose; } for ($loop = $start; $loop <= $end; $loop ++) { if ($loop > 0) { if ($this->curPage == $loop) { $output .= $this->curTagOpen . $loop . $this->curTagClose; // Current page } else { $n = ($loop == 1) ? "/{$this->firstFileName}" : "/" . $this->fileId . $loop . $this->fileExt; $output .= $this->numTagOpen . '<a href="' . $this->baseUrl . $n . '">' . $loop . '</a>' . $this->numTagClose; } } } if ($this->curPage < $this->totalPages) { $output .= $this->nextTagOpen . '<a href="' . $this->baseUrl . '/' . $this->fileId . ($this->curPage + 1) . $this->fileExt . '">' . $this->nextLink . '</a>' . $this->nextTagClose; } if (($this->curPage + $this->numLinks) < $this->totalPages) { $output .= $this->lastTagOpen . '<a href="' . $this->baseUrl . '/' . $this->fileId . $this->totalPages . $this->fileExt . '">' . $this->lastLink . '</a>' . $this->lastTagClose; } $output = preg_replace("#([^:])//+#", "\\1/", $output); $output = $this->fullTagOpen . $output . $this->fullTagClose; if ($this->pageSize > 1) { $output .= " <span>({$this->pageSize}条/页 共{$this->totalPages}页)</span> "; } $this->Base->pagesCode = $output; return ''; } } // End
01cms
01cms/branches/2.0/01mvc/lib/StaticPages.php
PHP
asf20
4,718
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Converts to and from JSON format. * * JSON (JavaScript Object Notation) is a lightweight data-interchange * format. It is easy for humans to read and write. It is easy for machines * to parse and generate. It is based on a subset of the JavaScript * Programming Language, Standard ECMA-262 3rd Edition - December 1999. * This feature can also be found in Python. JSON is a text format that is * completely language independent but uses conventions that are familiar * to programmers of the C-family of languages, including C, C++, C#, Java, * JavaScript, Perl, TCL, and many others. These properties make JSON an * ideal data-interchange language. * * This package provides a simple encoder and decoder for JSON notation. It * is intended for use with client-side Javascript applications that make * use of HTTPRequest to perform server communication functions - data can * be encoded into JSON notation for use in a client-side javascript, or * decoded from incoming Javascript requests. JSON format is native to * Javascript, and can be directly eval()'ed with no further parsing * overhead * * All strings should be in ASCII or UTF-8 format! * * LICENSE: Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: Redistributions of source code must retain the * above copyright notice, this list of conditions and the following * disclaimer. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * @package 01CMS * @subpackage system * @author Michal Migurski <mike-json@teczno.com> * @author Matt Knapp <mdknapp[at]gmail[dot]com> * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com> * @copyright 2005 Michal Migurski * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $ * @license http://www.opensource.org/licenses/bsd-license.php * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 */ /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_SLICE', 1); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_STR', 2); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_ARR', 3); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_OBJ', 4); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_CMT', 5); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_LOOSE_TYPE', 16); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_SUPPRESS_ERRORS', 32); /** * Converts to and from JSON format. * * Brief example of use: * * <code> * // create a new instance of Services_JSON * $json = new Services_JSON(); * * // convert a complexe value to JSON notation, and send it to the browser * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); * $output = $json->encode($value); * * print($output); * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] * * // accept incoming POST data, assumed to be in JSON notation * $input = file_get_contents('php://input', 1000000); * $value = $json->decode($input); * </code> */ class Services_JSON { /** * constructs a new JSON instance * * @param int $use object behavior flags; combine with boolean-OR * * possible values: * - SERVICES_JSON_LOOSE_TYPE: loose typing. * "{...}" syntax creates associative arrays * instead of objects in decode(). * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. * Values which can't be encoded (e.g. resources) * appear as NULL instead of throwing errors. * By default, a deeply-nested resource will * bubble up with an error, so all return values * from encode() should be checked with isError() */ function Services_JSON($use = 0) { $this->use = $use; } /** * convert a string from one UTF-16 char to one UTF-8 char * * Normally should be handled by mb_convert_encoding, but * provides a slower PHP-only method for installations * that lack the multibye string extension. * * @param string $utf16 UTF-16 character * @return string UTF-8 character * @access private */ function utf162utf8($utf16) { // oh please oh please oh please oh please oh please if(function_exists('mb_convert_encoding')) { return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); } $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); switch(true) { case ((0x7F & $bytes) == $bytes): // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x7F & $bytes); case (0x07FF & $bytes) == $bytes: // return a 2-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xC0 | (($bytes >> 6) & 0x1F)) . chr(0x80 | ($bytes & 0x3F)); case (0xFFFF & $bytes) == $bytes: // return a 3-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xE0 | (($bytes >> 12) & 0x0F)) . chr(0x80 | (($bytes >> 6) & 0x3F)) . chr(0x80 | ($bytes & 0x3F)); } // ignoring UTF-32 for now, sorry return ''; } /** * convert a string from one UTF-8 char to one UTF-16 char * * Normally should be handled by mb_convert_encoding, but * provides a slower PHP-only method for installations * that lack the multibye string extension. * * @param string $utf8 UTF-8 character * @return string UTF-16 character * @access private */ function utf82utf16($utf8) { // oh please oh please oh please oh please oh please if(function_exists('mb_convert_encoding')) { return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); } switch(strlen($utf8)) { case 1: // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return $utf8; case 2: // return a UTF-16 character from a 2-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x07 & (ord($utf8{0}) >> 2)) . chr((0xC0 & (ord($utf8{0}) << 6)) | (0x3F & ord($utf8{1}))); case 3: // return a UTF-16 character from a 3-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr((0xF0 & (ord($utf8{0}) << 4)) | (0x0F & (ord($utf8{1}) >> 2))) . chr((0xC0 & (ord($utf8{1}) << 6)) | (0x7F & ord($utf8{2}))); } // ignoring UTF-32 for now, sorry return ''; } /** * encodes an arbitrary variable into JSON format * * @param mixed $var any number, boolean, string, array, or object to be encoded. * see argument 1 to Services_JSON() above for array-parsing behavior. * if var is a strng, note that encode() always expects it * to be in ASCII or UTF-8 format! * * @return mixed JSON string representation of input var or an error if a problem occurs * @access public */ function encode($var) { switch (gettype($var)) { case 'boolean': return $var ? 'true' : 'false'; case 'NULL': return 'null'; case 'integer': return (int) $var; case 'double': case 'float': return (float) $var; case 'string': // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT $ascii = ''; $strlen_var = strlen($var); /* * Iterate over every character in the string, * escaping with a slash or encoding to UTF-8 where necessary */ for ($c = 0; $c < $strlen_var; ++$c) { $ord_var_c = ord($var{$c}); switch (true) { case $ord_var_c == 0x08: $ascii .= '\b'; break; case $ord_var_c == 0x09: $ascii .= '\t'; break; case $ord_var_c == 0x0A: $ascii .= '\n'; break; case $ord_var_c == 0x0C: $ascii .= '\f'; break; case $ord_var_c == 0x0D: $ascii .= '\r'; break; case $ord_var_c == 0x22: case $ord_var_c == 0x2F: case $ord_var_c == 0x5C: // double quote, slash, slosh $ascii .= '\\'.$var{$c}; break; case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): // characters U-00000000 - U-0000007F (same as ASCII) $ascii .= $var{$c}; break; case (($ord_var_c & 0xE0) == 0xC0): // characters U-00000080 - U-000007FF, mask 110XXXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1})); $c += 1; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF0) == 0xE0): // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2})); $c += 2; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF8) == 0xF0): // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3})); $c += 3; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFC) == 0xF8): // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4})); $c += 4; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFE) == 0xFC): // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4}), ord($var{$c + 5})); $c += 5; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; } } return '"'.$ascii.'"'; case 'array': /* * As per JSON spec if any array key is not an integer * we must treat the the whole array as an object. We * also try to catch a sparsely populated associative * array with numeric keys here because some JS engines * will create an array with empty indexes up to * max_index which can cause memory issues and because * the keys, which may be relevant, will be remapped * otherwise. * * As per the ECMA and JSON specification an object may * have any string as a property. Unfortunately due to * a hole in the ECMA specification if the key is a * ECMA reserved word or starts with a digit the * parameter is only accessible using ECMAScript's * bracket notation. */ // treat as a JSON object if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { $properties = array_map(array($this, 'name_value'), array_keys($var), array_values($var)); foreach($properties as $property) { if(Services_JSON::isError($property)) { return $property; } } return '{' . join(',', $properties) . '}'; } // treat it like a regular array $elements = array_map(array($this, 'encode'), $var); foreach($elements as $element) { if(Services_JSON::isError($element)) { return $element; } } return '[' . join(',', $elements) . ']'; case 'object': $vars = get_object_vars($var); $properties = array_map(array($this, 'name_value'), array_keys($vars), array_values($vars)); foreach($properties as $property) { if(Services_JSON::isError($property)) { return $property; } } return '{' . join(',', $properties) . '}'; default: return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) ? 'null' : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); } } /** * array-walking function for use in generating JSON-formatted name-value pairs * * @param string $name name of key to use * @param mixed $value reference to an array element to be encoded * * @return string JSON-formatted name-value pair, like '"name":value' * @access private */ function name_value($name, $value) { $encoded_value = $this->encode($value); if(Services_JSON::isError($encoded_value)) { return $encoded_value; } return $this->encode(strval($name)) . ':' . $encoded_value; } /** * reduce a string by removing leading and trailing comments and whitespace * * @param $str string string value to strip of comments and whitespace * * @return string string value stripped of comments and whitespace * @access private */ function reduce_string($str) { $str = preg_replace(array( // eliminate single line comments in '// ...' form '#^\s*//(.+)$#m', // eliminate multi-line comments in '/* ... */' form, at start of string '#^\s*/\*(.+)\*/#Us', // eliminate multi-line comments in '/* ... */' form, at end of string '#/\*(.+)\*/\s*$#Us' ), '', $str); // eliminate extraneous space return trim($str); } /** * decodes a JSON string into appropriate variable * * @param string $str JSON-formatted string * * @return mixed number, boolean, string, array, or object * corresponding to given JSON input string. * See argument 1 to Services_JSON() above for object-output behavior. * Note that decode() always returns strings * in ASCII or UTF-8 format! * @access public */ function decode($str) { $str = $this->reduce_string($str); switch (strtolower($str)) { case 'true': return true; case 'false': return false; case 'null': return null; default: $m = array(); if (is_numeric($str)) { // Lookie-loo, it's a number // This would work on its own, but I'm trying to be // good about returning integers where appropriate: // return (float)$str; // Return float or int, as appropriate return ((float)$str == (integer)$str) ? (integer)$str : (float)$str; } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { // STRINGS RETURNED IN UTF-8 FORMAT $delim = substr($str, 0, 1); $chrs = substr($str, 1, -1); $utf8 = ''; $strlen_chrs = strlen($chrs); for ($c = 0; $c < $strlen_chrs; ++$c) { $substr_chrs_c_2 = substr($chrs, $c, 2); $ord_chrs_c = ord($chrs{$c}); switch (true) { case $substr_chrs_c_2 == '\b': $utf8 .= chr(0x08); ++$c; break; case $substr_chrs_c_2 == '\t': $utf8 .= chr(0x09); ++$c; break; case $substr_chrs_c_2 == '\n': $utf8 .= chr(0x0A); ++$c; break; case $substr_chrs_c_2 == '\f': $utf8 .= chr(0x0C); ++$c; break; case $substr_chrs_c_2 == '\r': $utf8 .= chr(0x0D); ++$c; break; case $substr_chrs_c_2 == '\\"': case $substr_chrs_c_2 == '\\\'': case $substr_chrs_c_2 == '\\\\': case $substr_chrs_c_2 == '\\/': if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || ($delim == "'" && $substr_chrs_c_2 != '\\"')) { $utf8 .= $chrs{++$c}; } break; case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): // single, escaped unicode character $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) . chr(hexdec(substr($chrs, ($c + 4), 2))); $utf8 .= $this->utf162utf8($utf16); $c += 5; break; case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): $utf8 .= $chrs{$c}; break; case ($ord_chrs_c & 0xE0) == 0xC0: // characters U-00000080 - U-000007FF, mask 110XXXXX //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 2); ++$c; break; case ($ord_chrs_c & 0xF0) == 0xE0: // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 3); $c += 2; break; case ($ord_chrs_c & 0xF8) == 0xF0: // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 4); $c += 3; break; case ($ord_chrs_c & 0xFC) == 0xF8: // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 5); $c += 4; break; case ($ord_chrs_c & 0xFE) == 0xFC: // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 6); $c += 5; break; } } return $utf8; } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { // array, or object notation if ($str{0} == '[') { $stk = array(SERVICES_JSON_IN_ARR); $arr = array(); } else { if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $stk = array(SERVICES_JSON_IN_OBJ); $obj = array(); } else { $stk = array(SERVICES_JSON_IN_OBJ); $obj = new stdClass(); } } array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => 0, 'delim' => false)); $chrs = substr($str, 1, -1); $chrs = $this->reduce_string($chrs); if ($chrs == '') { if (reset($stk) == SERVICES_JSON_IN_ARR) { return $arr; } else { return $obj; } } //print("\nparsing {$chrs}\n"); $strlen_chrs = strlen($chrs); for ($c = 0; $c <= $strlen_chrs; ++$c) { $top = end($stk); $substr_chrs_c_2 = substr($chrs, $c, 2); if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { // found a comma that is not inside a string, array, etc., // OR we've reached the end of the character list $slice = substr($chrs, $top['where'], ($c - $top['where'])); array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); if (reset($stk) == SERVICES_JSON_IN_ARR) { // we are in an array, so just push an element onto the stack array_push($arr, $this->decode($slice)); } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { // we are in an object, so figure // out the property name and set an // element in an associative array, // for now $parts = array(); if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { // "name":value pair $key = $this->decode($parts[1]); $val = $this->decode($parts[2]); if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $obj[$key] = $val; } else { $obj->$key = $val; } } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { // name:value pair, where name is unquoted $key = $parts[1]; $val = $this->decode($parts[2]); if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $obj[$key] = $val; } else { $obj->$key = $val; } } } } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { // found a quote, and we are not inside a string array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); //print("Found start of string at {$c}\n"); } elseif (($chrs{$c} == $top['delim']) && ($top['what'] == SERVICES_JSON_IN_STR) && ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { // found a quote, we're in a string, and it's not escaped // we know that it's not escaped becase there is _not_ an // odd number of backslashes at the end of the string so far array_pop($stk); //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); } elseif (($chrs{$c} == '[') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a left-bracket, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); //print("Found start of array at {$c}\n"); } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { // found a right-bracket, and we're in an array array_pop($stk); //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } elseif (($chrs{$c} == '{') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a left-brace, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); //print("Found start of object at {$c}\n"); } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { // found a right-brace, and we're in an object array_pop($stk); //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } elseif (($substr_chrs_c_2 == '/*') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a comment start, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); $c++; //print("Found start of comment at {$c}\n"); } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { // found a comment end, and we're in one now array_pop($stk); $c++; for ($i = $top['where']; $i <= $c; ++$i) $chrs = substr_replace($chrs, ' ', $i, 1); //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } } if (reset($stk) == SERVICES_JSON_IN_ARR) { return $arr; } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { return $obj; } } } } /** * Ultimately, this should just call PEAR::isError() */ function isError($data, $code = null) { if (class_exists('pear')) { return PEAR::isError($data, $code); } elseif (is_object($data) && (get_class($data) == 'services_json_error' || is_subclass_of($data, 'services_json_error'))) { return true; } return false; } } if (class_exists('PEAR_Error')) { class Services_JSON_Error extends PEAR_Error { function Services_JSON_Error($message = 'unknown error', $code = null, $mode = null, $options = null, $userinfo = null) { parent::PEAR_Error($message, $code, $mode, $options, $userinfo); } } } else { /** * @todo Ultimately, this class shall be descended from PEAR_Error */ class Services_JSON_Error { function Services_JSON_Error($message = 'unknown error', $code = null, $mode = null, $options = null, $userinfo = null) { } } } ?>
01cms
01cms/branches/2.0/01mvc/lib/Services_JSON.php
PHP
asf20
34,815
<?php class String { private static $pinyins; function pinyin ($string, $head = 0, $close = 1) { $string = iconv('utf-8', 'gbk//ignore', $string); $returnString = ''; $string = trim($string); $slen = strlen($string); if ($slen < 2) { return $string; } if (count(self::$pinyins) == 0) { $fp = fopen(SYS_PATH . '/data/pinyin.dat', 'r'); while (! feof($fp)) { $line = trim(fgets($fp)); self::$pinyins[$line[0] . $line[1]] = substr($line, 3, strlen($line) - 3); } fclose($fp); } for ($i = 0; $i < $slen; $i ++) { if (ord($string[$i]) > 0x80) { $c = $string[$i] . $string[$i + 1]; $i ++; if (isset(self::$pinyins[$c])) { if ($head == 0) { $returnString .= self::$pinyins[$c]; } else { $returnString .= self::$pinyins[$c][0]; } } else { $returnString .= "_"; } } else if (eregi("[a-z0-9]", $string[$i])) { $returnString .= $string[$i]; } else { $returnString .= "_"; } } if ($close == 0) { unset(self::$pinyins); } return $returnString; } }
01cms
01cms/branches/2.0/01mvc/lib/String.php
PHP
asf20
1,723
<?php /** * 会话类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Session { /** * 写入Cookie * * @param string $key * @param string $value * @param int $keepTime 有效期(秒) * @param string $path * @return bool * @access public */ public static function putCookie ($key, $value, $keepTime = 300, $path = "/") { $status1 = setcookie($key, $value, time() + $keepTime, $path); $status2 = setcookie($key . '_c', encrypt($value), time() + $keepTime, $path); return ($status1 && $status2); } /** * 删除COOKIE * * @param string $key * @return bool * @access public */ public static function dropCookie ($key) { $status1 = setcookie($key, '', time() - 360000, "/"); $status2 = setcookie($key . '_c', '', time() - 360000, "/"); return ($status1 && $status2); } /** * 获取Cookie值 * * @param string $key * @return mix * @access public */ public static function getCookie ($key) { if (! isset($_COOKIE[$key]) || ! isset($_COOKIE[$key . '_c'])) { return; } if ($_COOKIE[$key . '_c'] != encrypt($_COOKIE[$key])) { return; } return $_COOKIE[$key]; } /** * 写入加密Cookie(设置验证码) * * @param string $key * @param string $value * @param int $keepTime 有效期(秒) * @param string $path * @return bool * @access public */ public static function setCode ($key, $value, $keepTime = 300, $path = "/") { return setcookie($key, encrypt(strtolower($value)), time() + $keepTime, $path); } /** * 检测Cookie值(检测验证码) * * @param string $key * @param string $value * @return bool * @access public */ public static function checkCode ($key, $value) { if (! isset($_COOKIE[$key])) { return FALSE; } $getedValue = $_COOKIE[$key]; setcookie($key, '', time() - 360000, "/"); return (encrypt(strtolower($value)) == $getedValue) ? true : false; } /** * 验证码 */ public static function validateCode () { //create captcha $consts = 'cdfgkmnpqrstwxyz23456'; $vowels = 'aek23456789'; for ($x = 0; $x < 6; $x ++) { $const[$x] = substr($consts, mt_rand(0, strlen($consts) - 1), 1); $vow[$x] = substr($vowels, mt_rand(0, strlen($vowels) - 1), 1); } $radomstring = $const[0] . $vow[0] . $const[2] . $const[1] . $vow[1] . $const[3] . $vow[3] . $const[4]; $string = substr($radomstring, 0, 4); //only display 4 str Session::setCode('validateCode', $string, 900); //set up image, the first number is the width and the second is the height $imageX = strlen($radomstring) * 8; //the image width $imageY = 20; //the image height $im = imagecreatetruecolor($imageX, $imageY); //creates two variables to store color $foregroundArr = array(imagecolorallocate($im, rand(0, 20), rand(0, 20), rand(0, 20)), imagecolorallocate($im, rand(0, 20), rand(0, 10), rand(245, 255)), imagecolorallocate($im, rand(245, 255), rand(0, 20), rand(0, 10)), imagecolorallocate($im, rand(245, 255), rand(0, 20), rand(245, 255))); $middleground = imagecolorallocate($im, rand(200, 160), rand(200, 160), rand(200, 160)); $middleground2 = imagecolorallocatealpha($im, rand(180, 140), rand(180, 140), rand(180, 140), 80); //fill image with bgcolor imagefill($im, 0, 0, imagecolorallocate($im, 250, 253, 254)); //writes string if (function_exists('imagettftext')) { imagettftext($im, 18, rand(30, - 30), 5, rand(14, 16), $foregroundArr[rand(0, 3)], SYS_PATH . '/data/font/vrinda.ttf', $string[0]); imagettftext($im, 12, rand(50, - 50), 20, rand(14, 16), $foregroundArr[rand(0, 3)], SYS_PATH . '/data/font/ARIALNI.TTF', $string[1]); imagettftext($im, 12, rand(50, - 50), 35, rand(14, 16), $foregroundArr[rand(0, 3)], SYS_PATH . '/data/font/ALGER.TTF', $string[2]); imagettftext($im, 12, rand(30, - 30), 50, rand(14, 16), $foregroundArr[rand(0, 3)], SYS_PATH . '/data/font/arial.ttf', $string[3]); } else { imagestring($im, 5, 3, floor(rand(0, 5)) - 1, $string[0], $foregroundArr[rand(0, 3)]); imagestring($im, 5, 16, floor(rand(0, 5)) - 1, $string[1], $foregroundArr[rand(0, 3)]); imagestring($im, 5, 23, floor(rand(0, 5)) - 1, $string[2], $foregroundArr[rand(0, 3)]); imagestring($im, 5, 33, floor(rand(0, 5)) - 1, $string[3], $foregroundArr[rand(0, 3)]); } //strikethrough $border = imagecolorallocate($im, 200, 200, 200); //imagefilledrectangle($aimg, 0, 0, $x_size - 1, $y_size - 1, $back); imagerectangle($im, 0, 0, $imageX - 1, $imageY - 1, $border); $pointcol = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255)); for ($i = 0; $i < 80; $i ++) { imagesetpixel($im, rand(2, $imageX - 2), rand(2, $imageX - 2), $pointcol); } //random shapes for ($x = 0; $x < 9; $x ++) { if (mt_rand(0, $x) % 2 == 0) { imageline($im, rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 999999)); imageellipse($im, rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 120), $middleground2); } else { imageline($im, rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 999999)); imageellipse($im, rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 120), $middleground); } } //output to browser header("content-type:image/png\r\n"); imagepng($im); imagedestroy($im); } }
01cms
01cms/branches/2.0/01mvc/lib/Session.php
PHP
asf20
6,453
<?php /** * 文件写操作类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Write { /** * 将PHP数组写入文件 * * @param string $filePath 文件路径 * @param array $array 数组值 * @param string $comment 文件注释 * @return int * @access public * @version 1.0.0 (2009-7-22) * @author rolong at vip.qq.com */ public function phpArray ($filePath, $array, $comment = '') { $string = var_export($array, TRUE); if(!empty($comment)) { $comment = str_replace("\r\n", "\n", $comment); $comment = str_replace("\n", "\n * ", $comment); $comment = "\n/**\n * {$comment}\n */\n"; } return file_put_contents($filePath, "<?php{$comment}\nreturn {$string};"); } } //End
01cms
01cms/branches/2.0/01mvc/lib/Write.php
PHP
asf20
978
<?php /** * 图片处理类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class ImageLib { public $imageLibrary = 'gd2'; public $libraryPath = ''; public $dynamicOutput = FALSE; public $sourceImage = ''; public $newImage = ''; public $width = ''; public $height = ''; public $quality = '100'; public $createThumb = FALSE; public $thumbMarker = '_thumb'; public $fullThumbPath; public $thumbPadColor = '#ffffff'; public $thumbWidth = ''; public $thumbHeight = ''; public $maintainRatio = TRUE; public $masterDim = 'auto'; public $rotationAngle = ''; public $xAxis = ''; public $yAxis = ''; public $wmText = ''; public $wmType = 'text'; public $wmXTransp = 4; public $wmYTransp = 4; public $wmOverlayPath = ''; public $wmFontPath = ''; public $wmFontSize = 17; public $wmVrtAlignment = 'B'; public $wmHorAlignment = 'C'; public $wmPadding = 5; public $wmHorOffset = 0; public $wmVrtOffset = 0; public $wmFontColor = '#ffffff'; public $wmShadowColor = ''; public $wmShadowDistance = 1; public $wmOpacity = 50; public $sourceFolder = ''; public $destFolder = ''; public $mimeType = ''; public $origWidth = ''; public $origHeight = ''; public $imageType = ''; public $sizeStr = ''; public $fullSrcPath = ''; public $fullDstPath = ''; public $createFnc = 'imagecreatetruecolor'; public $copyFnc = 'imagecopyresampled'; public $errorMsg = ''; public $wmUseDropShadow = FALSE; public $wmUseTruetype = FALSE; function clear () { $props = array('sourceFolder', 'destFolder', 'sourceImage', 'fullSrcPath', 'fullDstPath', 'newImage', 'imageType', 'sizeStr', 'quality', 'origWidth', 'origHeight', 'rotationAngle', 'xAxis', 'yAxis', 'createFnc', 'copyFnc', 'wmOverlayPath', 'wmUseTruetype', 'dynamicOutput', 'wmFontSize', 'wmText', 'wmVrtAlignment', 'wmHorAlignment', 'wmPadding', 'wmHorOffset', 'wmVrtOffset', 'wmFontColor', 'wmUseDropShadow', 'wmShadowColor', 'wmShadowDistance', 'wmOpacity'); foreach ($props as $val) { $this->$val = ''; } $this->masterDim = 'auto'; } function initialize ($props = array()) { if (count($props) > 0) { foreach ($props as $key => $val) { $this->$key = $val; } } if ($this->sourceImage == '') { $this->setError('源图片不存在'); return FALSE; } if (! function_exists('getimagesize')) { $this->setError('没有加载GD扩展'); return FALSE; } $this->imageLibrary = strtolower($this->imageLibrary); if (function_exists('realpath') and @realpath($this->sourceImage) !== FALSE) { $fullSourcePath = str_replace("\\", "/", realpath($this->sourceImage)); } else { $fullSourcePath = $this->sourceImage; } $x = explode('/', $fullSourcePath); $this->sourceImage = end($x); $this->sourceFolder = str_replace($this->sourceImage, '', $fullSourcePath); if (! $this->getImageProperties($this->sourceFolder . $this->sourceImage)) { return FALSE; } if ($this->newImage == '') { $this->destImage = $this->sourceImage; $this->destFolder = $this->sourceFolder; } else { if (strpos($this->newImage, '/') === FALSE) { $this->destFolder = $this->sourceFolder; $this->destImage = $this->newImage; } else { if (function_exists('realpath') and @realpath($this->newImage) !== FALSE) { $fullDestPath = str_replace("\\", "/", realpath($this->newImage)); } else { $fullDestPath = $this->newImage; } if (! preg_match("#\.(jpg|jpeg|gif|png)$#i", $fullDestPath)) { $this->destFolder = $fullDestPath . '/'; $this->destImage = $this->sourceImage; } else { $x = explode('/', $fullDestPath); $this->destImage = end($x); $this->destFolder = str_replace($this->destImage, '', $fullDestPath); } } } $xp = $this->explodeName($this->destImage); $filename = $xp['name']; $file_ext = $xp['ext']; $this->fullSrcPath = $this->sourceFolder . $this->sourceImage; $this->fullDstPath = $this->destFolder . $filename . $file_ext; if ($this->createThumb && $this->thumbMarker != '') { $this->fullThumbPath = $this->destFolder . $filename . $this->thumbMarker . $file_ext; } if ($this->maintainRatio === TRUE && ($this->width != '' and $this->height != '')) { $this->imageReproportion(); } if ($this->width == '') { $this->width = $this->origWidth; } if ($this->height == '') { $this->height = $this->origHeight; } $this->quality = trim(str_replace("%", "", $this->quality)); if ($this->quality == '' or $this->quality == 0 or ! is_numeric($this->quality)) { $this->quality = 90; } $this->xAxis = ($this->xAxis == '' or ! is_numeric($this->xAxis)) ? 0 : $this->xAxis; $this->yAxis = ($this->yAxis == '' or ! is_numeric($this->yAxis)) ? 0 : $this->yAxis; if ($this->wmFontColor != '') { if (strlen($this->wmFontColor) == 6) { $this->wmFontColor = '#' . $this->wmFontColor; } } if ($this->wmShadowColor != '') { if (strlen($this->wmShadowColor) == 6) { $this->wmShadowColor = '#' . $this->wmShadowColor; } } if ($this->wmOverlayPath != '') { $this->wmOverlayPath = str_replace("\\", "/", realpath($this->wmOverlayPath)); } if ($this->wmShadowColor != '') { $this->wmUseDropShadow = TRUE; } if ($this->wmFontPath != '') { $this->wmUseTruetype = TRUE; } return TRUE; } function resize () { $protocol = 'imageProcess' . ucfirst($this->imageLibrary); if (preg_match('/gd2$/i', $protocol)) { $protocol = 'imageProcessGd'; } return $this->$protocol('resize'); } function crop () { $protocol = 'imageProcess' . ucfirst($this->imageLibrary); if (preg_match('/gd2$/i', $protocol)) { $protocol = 'imageProcessGd'; } return $this->$protocol('crop'); } function rotate () { $degs = array(90, 180, 270, 'vrt', 'hor'); if ($this->rotationAngle == '' or ! in_array($this->rotationAngle, $degs)) { $this->setError('imglib_rotationAngle_required'); return FALSE; } if ($this->rotationAngle == 90 or $this->rotationAngle == 270) { $this->width = $this->origHeight; $this->height = $this->origWidth; } else { $this->width = $this->origWidth; $this->height = $this->origHeight; } if ($this->imageLibrary == 'imagemagick' or $this->imageLibrary == 'netpbm') { $protocol = 'image_process_' . $this->imageLibrary; return $this->$protocol('rotate'); } if ($this->rotationAngle == 'hor' or $this->rotationAngle == 'vrt') { return $this->imageMirrorGd(); } else { return $this->image_rotate_gd(); } } function imageProcessGd ($action = 'resize') { $v2Override = FALSE; if ($this->dynamicOutput === FALSE) { if ($this->origWidth == $this->width and $this->origHeight == $this->height) { if ($this->sourceImage != $this->newImage) { if (@copy($this->fullSrcPath, $this->fullDstPath)) { @chmod($this->fullDstPath, 0664); } } return TRUE; } } if ($action == 'crop') { $this->origWidth = $this->width; $this->origHeight = $this->height; if ($this->gdVersion() !== FALSE) { $gdVersion = str_replace('0', '', $this->gdVersion()); $v2Override = ($gdVersion == 2) ? TRUE : FALSE; } } else { $this->xAxis = 0; $this->yAxis = 0; } if (! ($srcImg = $this->imageCreateGd())) { return FALSE; } if ($this->origWidth > $this->width || $this->origHeight > $this->height) { if ($this->imageLibrary == 'gd2' and function_exists('imagecreatetruecolor')) { $create = 'imagecreatetruecolor'; $copy = 'imagecopyresampled'; } else { $create = 'imagecreate'; $copy = 'imagecopyresized'; } $dstImg = $create($this->width, $this->height); $copy($dstImg, $srcImg, 0, 0, $this->xAxis, $this->yAxis, $this->width, $this->height, $this->origWidth, $this->origHeight); if ($this->dynamicOutput == TRUE) { $this->image_display_gd($dstImg); } else { if (! $this->imageSaveGd($dstImg)) { return FALSE; } } imagedestroy($dstImg); imagedestroy($srcImg); @chmod($this->fullDstPath, 0664); } return TRUE; } function imageProcessImagemagick ($action = 'resize') { if ($this->libraryPath == '') { $this->setError('imglib_libpath_invalid'); return FALSE; } if (! preg_match("/convert$/i", $this->libraryPath)) { $this->libraryPath = rtrim($this->libraryPath, '/') . '/'; $this->libraryPath .= 'convert'; } $cmd = $this->libraryPath . " -quality " . $this->quality; if ($action == 'crop') { $cmd .= " -crop " . $this->width . "x" . $this->height . "+" . $this->xAxis . "+" . $this->yAxis . " \"$this->fullSrcPath\" \"$this->fullDstPath\" 2>&1"; } elseif ($action == 'rotate') { switch ($this->rotationAngle) { case 'hor': $angle = '-flop'; break; case 'vrt': $angle = '-flip'; break; default: $angle = '-rotate ' . $this->rotationAngle; break; } $cmd .= " " . $angle . " \"$this->fullSrcPath\" \"$this->fullDstPath\" 2>&1"; } else { $cmd .= " -resize " . $this->width . "x" . $this->height . " \"$this->fullSrcPath\" \"$this->fullDstPath\" 2>&1"; } $retval = 1; @exec($cmd, $output, $retval); if ($retval > 0) { $this->setError('imglib_image_process_failed'); return FALSE; } @chmod($this->fullDstPath, DIR_WRITE_MODE); return TRUE; } function imageProcessNetpbm ($action = 'resize') { if ($this->libraryPath == '') { $this->setError('imglib_libpath_invalid'); return FALSE; } switch ($this->imageType) { case 1: $cmd_in = 'giftopnm'; $cmd_out = 'ppmtogif'; break; case 2: $cmd_in = 'jpegtopnm'; $cmd_out = 'ppmtojpeg'; break; case 3: $cmd_in = 'pngtopnm'; $cmd_out = 'ppmtopng'; break; } if ($action == 'crop') { $cmd_inner = 'pnmcut -left ' . $this->xAxis . ' -top ' . $this->yAxis . ' -width ' . $this->width . ' -height ' . $this->height; } elseif ($action == 'rotate') { switch ($this->rotationAngle) { case 90: $angle = 'r270'; break; case 180: $angle = 'r180'; break; case 270: $angle = 'r90'; break; case 'vrt': $angle = 'tb'; break; case 'hor': $angle = 'lr'; break; } $cmd_inner = 'pnmflip -' . $angle . ' '; } else { $cmd_inner = 'pnmscale -xysize ' . $this->width . ' ' . $this->height; } $cmd = $this->libraryPath . $cmd_in . ' ' . $this->fullSrcPath . ' | ' . $cmd_inner . ' | ' . $cmd_out . ' > ' . $this->destFolder . 'netpbm.tmp'; $retval = 1; @exec($cmd, $output, $retval); if ($retval > 0) { $this->setError('imglib_image_process_failed'); return FALSE; } copy($this->destFolder . 'netpbm.tmp', $this->fullDstPath); unlink($this->destFolder . 'netpbm.tmp'); @chmod($this->fullDstPath, DIR_WRITE_MODE); return TRUE; } function imageRotateGd () { if (! function_exists('imagerotate')) { $this->setError('imglib_rotate_unsupported'); return FALSE; } if (! ($srcImg = $this->imageCreateGd())) { return FALSE; } $white = imagecolorallocate($srcImg, 255, 255, 255); $dstImg = imagerotate($srcImg, $this->rotationAngle, $white); if ($this->dynamicOutput == TRUE) { $this->image_display_gd($dstImg); } else { if (! $this->imageSaveGd($dstImg)) { return FALSE; } } imagedestroy($dstImg); imagedestroy($srcImg); @chmod($this->fullDstPath, DIR_WRITE_MODE); return true; } function imageMirrorGd () { if (! $srcImg = $this->imageCreateGd()) { return FALSE; } $width = $this->origWidth; $height = $this->origHeight; if ($this->rotationAngle == 'hor') { for ($i = 0; $i < $height; $i ++) { $left = 0; $right = $width - 1; while ($left < $right) { $cl = imagecolorat($srcImg, $left, $i); $cr = imagecolorat($srcImg, $right, $i); imagesetpixel($srcImg, $left, $i, $cr); imagesetpixel($srcImg, $right, $i, $cl); $left ++; $right --; } } } else { for ($i = 0; $i < $width; $i ++) { $top = 0; $bot = $height - 1; while ($top < $bot) { $ct = imagecolorat($srcImg, $i, $top); $cb = imagecolorat($srcImg, $i, $bot); imagesetpixel($srcImg, $i, $top, $cb); imagesetpixel($srcImg, $i, $bot, $ct); $top ++; $bot --; } } } if ($this->dynamicOutput == TRUE) { $this->image_display_gd($srcImg); } else { if (! $this->imageSaveGd($srcImg)) { return FALSE; } } imagedestroy($srcImg); @chmod($this->fullDstPath, DIR_WRITE_MODE); return TRUE; } function watermark () { if ($this->wmType == 'overlay') { return $this->overlayWatermark(); } else { return $this->textWatermark(); } } function overlayWatermark () { if (! function_exists('imagecolortransparent')) { $this->setError('imglib_gd_required'); return FALSE; } $this->getImageProperties(); $props = $this->getImageProperties($this->wmOverlayPath, TRUE); $wmImgType = $props['imageType']; $wmWidth = $props['width']; $wmHeight = $props['height']; $wm_img = $this->imageCreateGd($this->wmOverlayPath, $wmImgType); $srcImg = $this->imageCreateGd($this->fullSrcPath); $this->wmVrtAlignment = strtoupper(substr($this->wmVrtAlignment, 0, 1)); $this->wmHorAlignment = strtoupper(substr($this->wmHorAlignment, 0, 1)); if ($this->wmVrtAlignment == 'B') $this->wmVrtOffset = $this->wmVrtOffset * - 1; if ($this->wmHorAlignment == 'R') $this->wmHorOffset = $this->wmHorOffset * - 1; $xAxis = $this->wmHorOffset + $this->wmPadding; $yAxis = $this->wmVrtOffset + $this->wmPadding; switch ($this->wmVrtAlignment) { case 'T': break; case 'M': $yAxis += ($this->origHeight / 2) - ($wmHeight / 2); break; case 'B': $yAxis += $this->origHeight - $wmHeight; break; } switch ($this->wmHorAlignment) { case 'L': break; case 'C': $xAxis += ($this->origWidth / 2) - ($wmWidth / 2); break; case 'R': $xAxis += $this->origWidth - $wmWidth; break; } if ($wmImgType == 3 and function_exists('imagealphablending')) { @imagealphablending($srcImg, TRUE); } $rgba = imagecolorat($wm_img, $this->wmXTransp, $this->wmYTransp); $alpha = ($rgba & 0x7F000000) >> 24; if ($alpha > 0) { imagecopy($srcImg, $wm_img, $xAxis, $yAxis, 0, 0, $wmWidth, $wmHeight); } else { imagecolortransparent($wm_img, imagecolorat($wm_img, $this->wmXTransp, $this->wmYTransp)); imagecopymerge($srcImg, $wm_img, $xAxis, $yAxis, 0, 0, $wmWidth, $wmHeight, $this->wmOpacity); } if ($this->dynamicOutput == TRUE) { $this->image_display_gd($srcImg); } else { if (! $this->imageSaveGd($srcImg)) { return FALSE; } } imagedestroy($srcImg); imagedestroy($wm_img); return TRUE; } function textWatermark () { if (! ($srcImg = $this->imageCreateGd())) { return FALSE; } if ($this->wmUseTruetype == TRUE and ! file_exists($this->wmFontPath)) { $this->setError('字体文件不存在'); return FALSE; } $this->getImageProperties(); $this->wmFontColor = str_replace('#', '', $this->wmFontColor); $this->wmShadowColor = str_replace('#', '', $this->wmShadowColor); $R1 = hexdec(substr($this->wmFontColor, 0, 2)); $G1 = hexdec(substr($this->wmFontColor, 2, 2)); $B1 = hexdec(substr($this->wmFontColor, 4, 2)); $R2 = hexdec(substr($this->wmShadowColor, 0, 2)); $G2 = hexdec(substr($this->wmShadowColor, 2, 2)); $B2 = hexdec(substr($this->wmShadowColor, 4, 2)); $txtColor = imagecolorclosest($srcImg, $R1, $G1, $B1); $drpColor = imagecolorclosest($srcImg, $R2, $G2, $B2); if ($this->wmVrtAlignment == 'B') $this->wmVrtOffset = $this->wmVrtOffset * - 1; if ($this->wmHorAlignment == 'R') $this->wmHorOffset = $this->wmHorOffset * - 1; if ($this->wmUseTruetype == TRUE) { if ($this->wmFontSize == '') $this->wmFontSize = '17'; $fontwidth = $this->wmFontSize - ($this->wmFontSize / 4); $fontheight = $this->wmFontSize; $this->wmVrtOffset += $this->wmFontSize; } else { $fontwidth = imagefontwidth($this->wmFontSize); $fontheight = imagefontheight($this->wmFontSize); } $xAxis = $this->wmHorOffset + $this->wmPadding; $yAxis = $this->wmVrtOffset + $this->wmPadding; if ($this->wmUseDropShadow == FALSE) $this->wmShadowDistance = 0; $this->wmVrtAlignment = strtoupper(substr($this->wmVrtAlignment, 0, 1)); $this->wmHorAlignment = strtoupper(substr($this->wmHorAlignment, 0, 1)); switch ($this->wmVrtAlignment) { case "T": break; case "M": $yAxis += ($this->origHeight / 2) + ($fontheight / 2); break; case "B": $yAxis += ($this->origHeight - $fontheight - $this->wmShadowDistance - ($fontheight / 2)); break; } $x_shad = $xAxis + $this->wmShadowDistance; $y_shad = $yAxis + $this->wmShadowDistance; switch ($this->wmHorAlignment) { case "L": break; case "R": if ($this->wmUseDropShadow) $x_shad += ($this->origWidth - $fontwidth * strlen($this->wmText)); $xAxis += ($this->origWidth - $fontwidth * strlen($this->wmText)); break; case "C": if ($this->wmUseDropShadow) $x_shad += floor(($this->origWidth - $fontwidth * strlen($this->wmText)) / 2); $xAxis += floor(($this->origWidth - $fontwidth * strlen($this->wmText)) / 2); break; } if ($this->wmUseTruetype) { if ($this->wmUseDropShadow) imagettftext($srcImg, $this->wmFontSize, 0, $x_shad, $y_shad, $drpColor, $this->wmFontPath, $this->wmText); imagettftext($srcImg, $this->wmFontSize, 0, $xAxis, $yAxis, $txtColor, $this->wmFontPath, $this->wmText); } else { if ($this->wmUseDropShadow) imagestring($srcImg, $this->wmFontSize, $x_shad, $y_shad, $this->wmText, $drpColor); imagestring($srcImg, $this->wmFontSize, $xAxis, $yAxis, $this->wmText, $txtColor); } if ($this->dynamicOutput == TRUE) { $this->image_display_gd($srcImg); } else { $this->imageSaveGd($srcImg); } imagedestroy($srcImg); return TRUE; } function imageCreateGd ($path = '', $imageType = '') { if ($path == '') $path = $this->fullSrcPath; if ($imageType == '') $imageType = $this->imageType; switch ($imageType) { case 1: if (! function_exists('imagecreatefromgif')) { $this->setError(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported')); return FALSE; } return imagecreatefromgif($path); break; case 2: if (! function_exists('imagecreatefromjpeg')) { $this->setError(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported')); return FALSE; } return imagecreatefromjpeg($path); break; case 3: if (! function_exists('imagecreatefrompng')) { $this->setError(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported')); return FALSE; } return imagecreatefrompng($path); break; } $this->setError(array('imglib_unsupported_imagecreate')); return FALSE; } function imageSaveGd ($resource) { switch ($this->imageType) { case 1: if (! function_exists('imagegif')) { $this->setError(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported')); return FALSE; } if (! @imagegif($resource, $this->fullDstPath)) { $this->setError('imglib_save_failed'); return FALSE; } break; case 2: if (! function_exists('imagejpeg')) { $this->setError(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported')); return FALSE; } if (phpversion() == '4.4.1') { @touch($this->fullDstPath); // PHP 4.4.1 bug #35060 - workaround } if (! @imagejpeg($resource, $this->fullDstPath, $this->quality)) { $this->setError('imglib_save_failed'); return FALSE; } break; case 3: if (! function_exists('imagepng')) { $this->setError(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported')); return FALSE; } if (! @imagepng($resource, $this->fullDstPath)) { $this->setError('imglib_save_failed'); return FALSE; } break; default: $this->setError(array('imglib_unsupported_imagecreate')); return FALSE; break; } return TRUE; } function image_display_gd ($resource) { header("Content-Disposition: filename={$this->sourceImage};"); header("Content-Type: {$this->mimeType}"); header('Content-Transfer-Encoding: binary'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT'); switch ($this->imageType) { case 1: imagegif($resource); break; case 2: imagejpeg($resource, '', $this->quality); break; case 3: imagepng($resource); break; default: echo 'Unable to display the image'; break; } } function imageReproportion () { if (! is_numeric($this->width) or ! is_numeric($this->height) or $this->width == 0 or $this->height == 0) return; if (! is_numeric($this->origWidth) or ! is_numeric($this->origHeight) or $this->origWidth == 0 or $this->origHeight == 0) return; $newWidth = ceil($this->origWidth * $this->height / $this->origHeight); $newHeight = ceil($this->width * $this->origHeight / $this->origWidth); $ratio = (($this->origHeight / $this->origWidth) - ($this->height / $this->width)); if ($this->masterDim != 'width' and $this->masterDim != 'height') { $this->masterDim = ($ratio < 0) ? 'width' : 'height'; } if (($this->width != $newWidth) and ($this->height != $newHeight)) { if ($this->masterDim == 'height') { $this->width = $newWidth; } else { $this->height = $newHeight; } } } function getImageProperties ($path = '', $return = FALSE) { if ($path == '') { $path = $this->fullSrcPath; } if (! file_exists($path)) { $this->setError('图片不存在'); return FALSE; } $vals = @getimagesize($path); $types = array(1=>'gif', 2=>'jpeg', 3=>'png'); $mime = (isset($types[$vals['2']])) ? 'image/' . $types[$vals['2']] : 'image/jpg'; if ($return == TRUE) { $v['width'] = $vals['0']; $v['height'] = $vals['1']; $v['imageType'] = $vals['2']; $v['sizeStr'] = $vals['3']; $v['mimeType'] = $mime; return $v; } $this->origWidth = $vals['0']; $this->origHeight = $vals['1']; $this->imageType = $vals['2']; $this->sizeStr = $vals['3']; $this->mimeType = $mime; return TRUE; } function sizeCalculator ($vals) { if (! is_array($vals)) { return; } $allowed = array('newWidth', 'newHeight', 'width', 'height'); foreach ($allowed as $item) { if (! isset($vals[$item]) or $vals[$item] == '') $vals[$item] = 0; } if ($vals['width'] == 0 or $vals['height'] == 0) { return $vals; } if ($vals['newWidth'] == 0) { $vals['newWidth'] = ceil($vals['width'] * $vals['newHeight'] / $vals['height']); } elseif ($vals['newHeight'] == 0) { $vals['newHeight'] = ceil($vals['newWidth'] * $vals['height'] / $vals['width']); } return $vals; } function explodeName ($sourceImage) { $ext = strrchr($sourceImage, '.'); $name = ($ext === FALSE) ? $sourceImage : substr($sourceImage, 0, - strlen($ext)); return array('ext'=>$ext, 'name'=>$name); } function gdLoaded () { if (! extension_loaded('gd')) { if (! dl('gd.so')) { return FALSE; } } return TRUE; } function thumb () { $srcFile = $this->fullSrcPath; $toFile = $this->fullThumbPath; $targetWidth = $this->thumbWidth; $targetHeight = $this->thumbHeight; switch ($this->imageType) { case 1: { $img = imagecreatefromgif($srcFile); break; } case 2: { $img = imagecreatefromjpeg($srcFile); break; } case 3: { $img = imagecreatefrompng($srcFile); break; } case 6: { $img = imagecreatefromwbmp($srcFile); break; } } $width = imagesx($img); $height = imagesy($img); if (! $width || ! $height) { return false; } $targetRatio = $targetWidth / $targetHeight; $imgRatio = $width / $height; if ($targetRatio > $imgRatio) { $newHeight = $targetHeight; $newWidth = $imgRatio * $targetHeight; } else { $newHeight = $targetWidth / $imgRatio; $newWidth = $targetWidth; } if ($newHeight > $targetHeight) { $newHeight = $targetHeight; } if ($newWidth > $targetWidth) { $newHeight = $targetWidth; } $newImg = imagecreatetruecolor($targetWidth, $targetHeight); $padColor = str_replace('#', '', $this->thumbPadColor); $R = hexdec(substr($padColor, 0, 2)); $G = hexdec(substr($padColor, 2, 2)); $B = hexdec(substr($padColor, 4, 2)); $color = ImageColorAllocate($newImg, $R, $G, $B); if (! @imagefilledrectangle($newImg, 0, 0, $targetWidth - 1, $targetHeight - 1, $color)) { return false; } if (! @imagecopyresampled($newImg, $img, ($targetWidth - $newWidth) / 2, ($targetHeight - $newHeight) / 2, 0, 0, $newWidth, $newHeight, $width, $height)) { return false; } switch ($this->imageType) { case 1: { imagegif($newImg, $toFile); break; } case 2: { imagejpeg($newImg, $toFile, 100); break; } case 3: { imagepng($newImg, $toFile); break; } case 6: { imagebmp($newImg, $toFile); break; } default: { return false; } } imagedestroy($newImg); imagedestroy($img); return true; } function gdVersion () { if (function_exists('gd_info')) { $gdVersion = @gd_info(); $gdVersion = preg_replace("/\D/", "", $gdVersion['GD Version']); return $gdVersion; } return FALSE; } function setError ($msg) { if (is_array($msg)) { foreach ($msg as $val) { $this->errorMsg .= ' ' . $val; } } else { $this->errorMsg = $msg; } } } // END ImageLib Class
01cms
01cms/branches/2.0/01mvc/lib/ImageLib.php
PHP
asf20
36,305
<?php /** * Project: Smarty: the PHP compiling template engine * File: Smarty.class.php * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For questions, help, comments, discussion, etc., please join the * Smarty mailing list. Send a blank e-mail to * smarty-discussion-subscribe@googlegroups.com * * @link http://www.smarty.net/ * @copyright 2001-2005 New Digital Group, Inc. * @author Monte Ohrt <monte at ohrt dot com> * @author Andrei Zmievski <andrei@php.net> * @package Smarty * @version 2.6.22 */ /* $Id: Smarty.class.php 2785 2008-09-18 21:04:12Z Uwe.Tews $ */ /** * DIR_SEP isn't used anymore, but third party apps might */ if (! defined('DIR_SEP')) { define('DIR_SEP', DIRECTORY_SEPARATOR); } /** * set SMARTY_DIR to absolute path to Smarty library files. * if not defined, include_path will be used. Sets SMARTY_DIR only if user * application has not already defined it. */ if (! defined('SMARTY_DIR')) { define('SMARTY_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR); } if (! defined('SMARTY_CORE_DIR')) { define('SMARTY_CORE_DIR', SMARTY_DIR . 'internals' . DIRECTORY_SEPARATOR); } define('SMARTY_PHP_PASSTHRU', 0); define('SMARTY_PHP_QUOTE', 1); define('SMARTY_PHP_REMOVE', 2); define('SMARTY_PHP_ALLOW', 3); /** * @package Smarty */ class Smarty { /**#@+ * Smarty Configuration Section */ /** * The name of the directory where templates are located. * * @var string */ public $template_dir = 'templates'; /** * The directory where compiled templates are located. * * @var string */ public $compile_dir = 'templates_c'; /** * The directory where config files are located. * * @var string */ public $config_dir = 'configs'; /** * An array of directories searched for plugins. * * @var array */ public $plugins_dir = array('plugins'); /** * If debugging is enabled, a debug console window will display * when the page loads (make sure your browser allows unrequested * popup windows) * * @var boolean */ public $debugging = false; /** * When set, smarty does uses this value as error_reporting-level. * * @var boolean */ public $error_reporting = null; /** * This is the path to the debug console template. If not set, * the default one will be used. * * @var string */ public $debug_tpl = ''; /** * This determines if debugging is enable-able from the browser. * <ul> * <li>NONE => no debugging control allowed</li> * <li>Url => enable debugging when SMARTY_DEBUG is found in the Url.</li> * </ul> * @link http://www.foo.dom/index.php?SMARTY_DEBUG * @var string */ public $debugging_ctrl = 'NONE'; /** * This tells Smarty whether to check for recompiling or not. Recompiling * does not need to happen unless a template or config file is changed. * Typically you enable this during development, and disable for * production. * * @var boolean */ public $compile_check = true; /** * This forces templates to compile every time. Useful for development * or debugging. * * @var boolean */ public $force_compile = false; /** * This enables template caching. * <ul> * <li>0 = no caching</li> * <li>1 = use class cache_lifetime value</li> * <li>2 = use cache_lifetime in cache file</li> * </ul> * @var integer */ public $caching = 0; /** * The name of the directory for cache files. * * @var string */ public $cache_dir = 'cache'; /** * This is the number of seconds cached content will persist. * <ul> * <li>0 = always regenerate cache</li> * <li>-1 = never expires</li> * </ul> * * @var integer */ public $cache_lifetime = 3600; /** * Only used when $caching is enabled. If true, then If-Modified-Since headers * are respected with cached content, and appropriate HTTP headers are sent. * This way repeated hits to a cached page do not send the entire page to the * client every time. * * @var boolean */ public $cache_modified_check = false; /** * This determines how Smarty handles "<?php ... ?>" tags in templates. * possible values: * <ul> * <li>SMARTY_PHP_PASSTHRU -> print tags as plain text</li> * <li>SMARTY_PHP_QUOTE -> escape tags as entities</li> * <li>SMARTY_PHP_REMOVE -> remove php tags</li> * <li>SMARTY_PHP_ALLOW -> execute php tags</li> * </ul> * * @var integer */ public $php_handling = SMARTY_PHP_PASSTHRU; /** * This enables template security. When enabled, many things are restricted * in the templates that normally would go unchecked. This is useful when * untrusted parties are editing templates and you want a reasonable level * of security. (no direct execution of PHP in templates for example) * * @var boolean */ public $security = false; /** * This is the list of template directories that are considered secure. This * is used only if {@link $security} is enabled. One directory per array * element. {@link $template_dir} is in this list implicitly. * * @var array */ public $secure_dir = array(); /** * These are the security settings for Smarty. They are used only when * {@link $security} is enabled. * * @var array */ public $security_settings = array('PHP_HANDLING' => false , 'IF_FUNCS' => array('array' , 'list' , 'isset' , 'empty' , 'count' , 'sizeof' , 'in_array' , 'is_array' , 'true' , 'false' , 'null') , 'INCLUDE_ANY' => false , 'PHP_TAGS' => false , 'MODIFIER_FUNCS' => array('count') , 'ALLOW_CONSTANTS' => false); /** * This is an array of directories where trusted php scripts reside. * {@link $security} is disabled during their inclusion/execution. * * @var array */ public $trusted_dir = array(); /** * The left delimiter used for the template tags. * * @var string */ public $left_delimiter = '{'; /** * The right delimiter used for the template tags. * * @var string */ public $right_delimiter = '}'; /** * The order in which request variables are registered, similar to * variables_order in php.ini E = Environment, G = GET, P = POST, * C = Cookies, S = Server * * @var string */ public $request_vars_order = 'EGPCS'; /** * Indicates wether $HTTP_*_VARS[] (request_use_auto_globals=false) * are uses as request-vars or $_*[]-vars. note: if * request_use_auto_globals is true, then $request_vars_order has * no effect, but the php-ini-value "gpc_order" * * @var boolean */ public $request_use_auto_globals = true; /** * Set this if you want different sets of compiled files for the same * templates. This is useful for things like different languages. * Instead of creating separate sets of templates per language, you * set different compile_ids like 'en' and 'de'. * * @var string */ public $compile_id = null; /** * This tells Smarty whether or not to use sub dirs in the cache/ and * templates_c/ directories. sub directories better organized, but * may not work well with PHP safe mode enabled. * * @var boolean * */ public $use_sub_dirs = false; /** * This is a list of the modifiers to apply to all template variables. * Put each modifier in a separate array element in the order you want * them applied. example: <code>array('escape:"htmlall"');</code> * * @var array */ public $default_modifiers = array(); /** * This is the resource type to be used when not specified * at the beginning of the resource path. examples: * $smarty->display('file:index.tpl'); * $smarty->display('db:index.tpl'); * $smarty->display('index.tpl'); // will use default resource type * {include file="file:index.tpl"} * {include file="db:index.tpl"} * {include file="index.tpl"} {* will use default resource type *} * * @var array */ public $default_resource_type = 'file'; /** * The function used for cache file handling. If not set, built-in caching is used. * * @var null|string function name */ public $cache_handler_func = null; /** * This indicates which filters are automatically loaded into Smarty. * * @var array array of filter names */ public $autoload_filters = array(); /**#@+ * @var boolean */ /** * This tells if config file vars of the same name overwrite each other or not. * if disabled, same name variables are accumulated in an array. */ public $config_overwrite = true; /** * This tells whether or not to automatically booleanize config file variables. * If enabled, then the strings "on", "true", and "yes" are treated as boolean * true, and "off", "false" and "no" are treated as boolean false. */ public $config_booleanize = true; /** * This tells whether hidden sections [.foobar] are readable from the * tempalates or not. Normally you would never allow this since that is * the point behind hidden sections: the application can access them, but * the templates cannot. */ public $config_read_hidden = false; /** * This tells whether or not automatically fix newlines in config files. * It basically converts \r (mac) or \r\n (dos) to \n */ public $config_fix_newlines = true; /**#@-*/ /** * If a template cannot be found, this PHP function will be executed. * Useful for creating templates on-the-fly or other special action. * * @var string function name */ public $default_template_handler_func = ''; /** * The file that contains the compiler class. This can a full * pathname, or relative to the php_include path. * * @var string */ public $compiler_file = 'Smarty_Compiler.class.php'; /** * The class used for compiling templates. * * @var string */ public $compiler_class = 'Smarty_Compiler'; /** * The class used to load config vars. * * @var string */ public $config_class = 'Config_File'; /**#@+ * END Smarty Configuration Section * There should be no need to touch anything below this line. * @access private */ /** * where assigned template vars are kept * * @var array */ public $_tpl_vars = array(); /** * stores run-time $smarty.* vars * * @var null|array */ public $_smarty_vars = null; /** * keeps track of sections * * @var array */ public $_sections = array(); /** * keeps track of foreach blocks * * @var array */ public $_foreach = array(); /** * keeps track of tag hierarchy * * @var array */ public $_tag_stack = array(); /** * configuration object * * @var Config_file */ public $_conf_obj = null; /** * loaded configuration settings * * @var array */ public $_config = array(array('vars' => array() , 'files' => array())); /** * md5 checksum of the string 'Smarty' * * @var string */ public $_smarty_md5 = 'f8d698aea36fcbead2b9d5359ffca76f'; /** * Smarty version number * * @var string */ public $_version = '2.6.22'; /** * current template inclusion depth * * @var integer */ public $_inclusion_depth = 0; /** * for different compiled templates * * @var string */ public $_compile_id = null; /** * text in Url to enable debug mode * * @var string */ public $_smarty_debug_id = 'SMARTY_DEBUG'; /** * debugging information for debug console * * @var array */ public $_smarty_debug_info = array(); /** * info that makes up a cache file * * @var array */ public $_cache_info = array(); /** * default file permissions * * @var integer */ public $_file_perms = 0644; /** * default dir permissions * * @var integer */ public $_dir_perms = 0771; /** * registered objects * * @var array */ public $_reg_objects = array(); /** * table keeping track of plugins * * @var array */ public $_plugins = array('modifier' => array() , 'function' => array() , 'block' => array() , 'compiler' => array() , 'prefilter' => array() , 'postfilter' => array() , 'outputfilter' => array() , 'resource' => array() , 'insert' => array()); /** * cache serials * * @var array */ public $_cache_serials = array(); /** * name of optional cache include file * * @var string */ public $_cache_include = null; /** * indicate if the current code is used in a compiled * include * * @var string */ public $_cache_including = false; /**#@-*/ /** * The class constructor. */ function Smarty () { $this->assign('SCRIPT_NAME', isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : @$GLOBALS['HTTP_SERVER_VARS']['SCRIPT_NAME']); } /** * assigns values to template variables * * @param array|string $tpl_var the template variable name(s) * @param mixed $value the value to assign */ function assign ($tpl_var, $value = null) { if (is_array($tpl_var)) { foreach ($tpl_var as $key => $val) { if ($key != '') { $this->_tpl_vars[$key] = $val; } } } else { if ($tpl_var != '') $this->_tpl_vars[$tpl_var] = $value; } } /** * assigns values to template variables by reference * * @param string $tpl_var the template variable name * @param mixed $value the referenced value to assign */ function assign_by_ref ($tpl_var, &$value) { if ($tpl_var != '') $this->_tpl_vars[$tpl_var] = &$value; } /** * appends values to template variables * * @param array|string $tpl_var the template variable name(s) * @param mixed $value the value to append */ function append ($tpl_var, $value = null, $merge = false) { if (is_array($tpl_var)) { // $tpl_var is an array, ignore $value foreach ($tpl_var as $_key => $_val) { if ($_key != '') { if (! @is_array($this->_tpl_vars[$_key])) { settype($this->_tpl_vars[$_key], 'array'); } if ($merge && is_array($_val)) { foreach ($_val as $_mkey => $_mval) { $this->_tpl_vars[$_key][$_mkey] = $_mval; } } else { $this->_tpl_vars[$_key][] = $_val; } } } } else { if ($tpl_var != '' && isset($value)) { if (! @is_array($this->_tpl_vars[$tpl_var])) { settype($this->_tpl_vars[$tpl_var], 'array'); } if ($merge && is_array($value)) { foreach ($value as $_mkey => $_mval) { $this->_tpl_vars[$tpl_var][$_mkey] = $_mval; } } else { $this->_tpl_vars[$tpl_var][] = $value; } } } } /** * appends values to template variables by reference * * @param string $tpl_var the template variable name * @param mixed $value the referenced value to append */ function append_by_ref ($tpl_var, &$value, $merge = false) { if ($tpl_var != '' && isset($value)) { if (! @is_array($this->_tpl_vars[$tpl_var])) { settype($this->_tpl_vars[$tpl_var], 'array'); } if ($merge && is_array($value)) { foreach ($value as $_key => $_val) { $this->_tpl_vars[$tpl_var][$_key] = &$value[$_key]; } } else { $this->_tpl_vars[$tpl_var][] = &$value; } } } /** * clear the given assigned template variable. * * @param string $tpl_var the template variable to clear */ function clear_assign ($tpl_var) { if (is_array($tpl_var)) foreach ($tpl_var as $curr_var) unset($this->_tpl_vars[$curr_var]); else unset($this->_tpl_vars[$tpl_var]); } /** * Registers custom function to be used in templates * * @param string $function the name of the template function * @param string $function_impl the name of the PHP function to register */ function register_function ($function, $function_impl, $cacheable = true, $cache_attrs = null) { $this->_plugins['function'][$function] = array($function_impl , null , null , false , $cacheable , $cache_attrs); } /** * Unregisters custom function * * @param string $function name of template function */ function unregister_function ($function) { unset($this->_plugins['function'][$function]); } /** * Registers object to be used in templates * * @param string $object name of template object * @param object &$object_impl the referenced PHP object to register * @param null|array $allowed list of allowed methods (empty = all) * @param boolean $smarty_args smarty argument format, else traditional * @param null|array $block_functs list of methods that are block format */ function register_object ($object, &$object_impl, $allowed = array(), $smarty_args = true, $block_methods = array()) { settype($allowed, 'array'); settype($smarty_args, 'boolean'); $this->_reg_objects[$object] = array(&$object_impl , $allowed , $smarty_args , $block_methods); } /** * Unregisters object * * @param string $object name of template object */ function unregister_object ($object) { unset($this->_reg_objects[$object]); } /** * Registers block function to be used in templates * * @param string $block name of template block * @param string $block_impl PHP function to register */ function register_block ($block, $block_impl, $cacheable = true, $cache_attrs = null) { $this->_plugins['block'][$block] = array($block_impl , null , null , false , $cacheable , $cache_attrs); } /** * Unregisters block function * * @param string $block name of template function */ function unregister_block ($block) { unset($this->_plugins['block'][$block]); } /** * Registers compiler function * * @param string $function name of template function * @param string $function_impl name of PHP function to register */ function register_compiler_function ($function, $function_impl, $cacheable = true) { $this->_plugins['compiler'][$function] = array($function_impl , null , null , false , $cacheable); } /** * Unregisters compiler function * * @param string $function name of template function */ function unregister_compiler_function ($function) { unset($this->_plugins['compiler'][$function]); } /** * Registers modifier to be used in templates * * @param string $modifier name of template modifier * @param string $modifier_impl name of PHP function to register */ function register_modifier ($modifier, $modifier_impl) { $this->_plugins['modifier'][$modifier] = array($modifier_impl , null , null , false); } /** * Unregisters modifier * * @param string $modifier name of template modifier */ function unregister_modifier ($modifier) { unset($this->_plugins['modifier'][$modifier]); } /** * Registers a resource to fetch a template * * @param string $type name of resource * @param array $functions array of functions to handle resource */ function register_resource ($type, $functions) { if (count($functions) == 4) { $this->_plugins['resource'][$type] = array($functions , false); } elseif (count($functions) == 5) { $this->_plugins['resource'][$type] = array(array(array(&$functions[0] , $functions[1]) , array(&$functions[0] , $functions[2]) , array(&$functions[0] , $functions[3]) , array(&$functions[0] , $functions[4])) , false); } else { $this->trigger_error("malformed function-list for '$type' in register_resource"); } } /** * Unregisters a resource * * @param string $type name of resource */ function unregister_resource ($type) { unset($this->_plugins['resource'][$type]); } /** * Registers a prefilter function to apply * to a template before compiling * * @param callback $function */ function register_prefilter ($function) { $this->_plugins['prefilter'][$this->_get_filter_name($function)] = array($function , null , null , false); } /** * Unregisters a prefilter function * * @param callback $function */ function unregister_prefilter ($function) { unset($this->_plugins['prefilter'][$this->_get_filter_name($function)]); } /** * Registers a postfilter function to apply * to a compiled template after compilation * * @param callback $function */ function register_postfilter ($function) { $this->_plugins['postfilter'][$this->_get_filter_name($function)] = array($function , null , null , false); } /** * Unregisters a postfilter function * * @param callback $function */ function unregister_postfilter ($function) { unset($this->_plugins['postfilter'][$this->_get_filter_name($function)]); } /** * Registers an output filter function to apply * to a template output * * @param callback $function */ function register_outputfilter ($function) { $this->_plugins['outputfilter'][$this->_get_filter_name($function)] = array($function , null , null , false); } /** * Unregisters an outputfilter function * * @param callback $function */ function unregister_outputfilter ($function) { unset($this->_plugins['outputfilter'][$this->_get_filter_name($function)]); } /** * load a filter of specified type and name * * @param string $type filter type * @param string $name filter name */ function load_filter ($type, $name) { switch ($type) { case 'output' : $_params = array('plugins' => array(array($type . 'filter' , $name , null , null , false))); require_once (SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins($_params, $this); break; case 'pre' : case 'post' : if (! isset($this->_plugins[$type . 'filter'][$name])) $this->_plugins[$type . 'filter'][$name] = false; break; } } /** * clear cached content for the given template and cache id * * @param string $tpl_file name of template file * @param string $cache_id name of cache_id * @param string $compile_id name of compile_id * @param string $exp_time expiration time * @return boolean */ function clear_cache ($tpl_file = null, $cache_id = null, $compile_id = null, $exp_time = null) { if (! isset($compile_id)) $compile_id = $this->compile_id; if (! isset($tpl_file)) $compile_id = null; $_auto_id = $this->_get_auto_id($cache_id, $compile_id); if (! empty($this->cache_handler_func)) { return call_user_func_array($this->cache_handler_func, array('clear' , &$this , &$dummy , $tpl_file , $cache_id , $compile_id , $exp_time)); } else { $_params = array('auto_base' => $this->cache_dir , 'auto_source' => $tpl_file , 'auto_id' => $_auto_id , 'exp_time' => $exp_time); require_once (SMARTY_CORE_DIR . 'core.rm_auto.php'); return smarty_core_rm_auto($_params, $this); } } /** * clear the entire contents of cache (all templates) * * @param string $exp_time expire time * @return boolean results of {@link smarty_core_rm_auto()} */ function clear_all_cache ($exp_time = null) { return $this->clear_cache(null, null, null, $exp_time); } /** * test to see if valid cache exists for this template * * @param string $tpl_file name of template file * @param string $cache_id * @param string $compile_id * @return string|false results of {@link _read_cache_file()} */ function is_cached ($tpl_file, $cache_id = null, $compile_id = null) { if (! $this->caching) return false; if (! isset($compile_id)) $compile_id = $this->compile_id; $_params = array('tpl_file' => $tpl_file , 'cache_id' => $cache_id , 'compile_id' => $compile_id); require_once (SMARTY_CORE_DIR . 'core.read_cache_file.php'); return smarty_core_read_cache_file($_params, $this); } /** * clear all the assigned template variables. * */ function clear_all_assign () { $this->_tpl_vars = array(); } /** * clears compiled version of specified template resource, * or all compiled template files if one is not specified. * This function is for advanced use only, not normally needed. * * @param string $tpl_file * @param string $compile_id * @param string $exp_time * @return boolean results of {@link smarty_core_rm_auto()} */ function clear_compiled_tpl ($tpl_file = null, $compile_id = null, $exp_time = null) { if (! isset($compile_id)) { $compile_id = $this->compile_id; } $_params = array('auto_base' => $this->compile_dir , 'auto_source' => $tpl_file , 'auto_id' => $compile_id , 'exp_time' => $exp_time , 'extensions' => array('.inc' , '.php')); require_once (SMARTY_CORE_DIR . 'core.rm_auto.php'); return smarty_core_rm_auto($_params, $this); } /** * Checks whether requested template exists. * * @param string $tpl_file * @return boolean */ function template_exists ($tpl_file) { $_params = array('resource_name' => $tpl_file , 'quiet' => true , 'get_source' => false); return $this->_fetch_resource_info($_params); } /** * Returns an array containing template variables * * @param string $name * @param string $type * @return array */ function &get_template_vars ($name = null) { if (! isset($name)) { return $this->_tpl_vars; } elseif (isset($this->_tpl_vars[$name])) { return $this->_tpl_vars[$name]; } else { // var non-existant, return valid reference $_tmp = null; return $_tmp; } } /** * Returns an array containing config variables * * @param string $name * @param string $type * @return array */ function &get_config_vars ($name = null) { if (! isset($name) && is_array($this->_config[0])) { return $this->_config[0]['vars']; } else if (isset($this->_config[0]['vars'][$name])) { return $this->_config[0]['vars'][$name]; } else { // var non-existant, return valid reference $_tmp = null; return $_tmp; } } /** * trigger Smarty error * * @param string $error_msg * @param integer $error_type */ function trigger_error ($error_msg, $error_type = E_USER_WARNING) { trigger_error("Smarty error: $error_msg", $error_type); } /** * executes & displays the template results * * @param string $resource_name * @param string $cache_id * @param string $compile_id */ function display ($resource_name, $cache_id = null, $compile_id = null) { $this->fetch($resource_name, $cache_id, $compile_id, true); } /** * executes & returns or displays the template results * * @param string $resource_name * @param string $cache_id * @param string $compile_id * @param boolean $display */ function fetch ($resource_name, $cache_id = null, $compile_id = null, $display = false) { static $_cache_info = array(); $_smarty_old_error_level = $this->debugging ? error_reporting() : error_reporting(isset($this->error_reporting) ? $this->error_reporting : error_reporting() & ~ E_NOTICE); if (! $this->debugging && $this->debugging_ctrl == 'Url') { $_query_string = $this->request_use_auto_globals ? $_SERVER['QUERY_STRING'] : $GLOBALS['HTTP_SERVER_VARS']['QUERY_STRING']; if (@strstr($_query_string, $this->_smarty_debug_id)) { if (@strstr($_query_string, $this->_smarty_debug_id . '=on')) { // enable debugging for this browser session @setcookie('SMARTY_DEBUG', true); $this->debugging = true; } elseif (@strstr($_query_string, $this->_smarty_debug_id . '=off')) { // disable debugging for this browser session @setcookie('SMARTY_DEBUG', false); $this->debugging = false; } else { // enable debugging for this page $this->debugging = true; } } else { $this->debugging = (bool) ($this->request_use_auto_globals ? @$_COOKIE['SMARTY_DEBUG'] : @$GLOBALS['HTTP_COOKIE_VARS']['SMARTY_DEBUG']); } } if ($this->debugging) { // capture time for debugging info $_params = array(); require_once (SMARTY_CORE_DIR . 'core.get_microtime.php'); $_debug_start_time = smarty_core_get_microtime($_params, $this); $this->_smarty_debug_info[] = array('type' => 'template' , 'filename' => $resource_name , 'depth' => 0); $_included_tpls_idx = count($this->_smarty_debug_info) - 1; } if (! isset($compile_id)) { $compile_id = $this->compile_id; } $this->_compile_id = $compile_id; $this->_inclusion_depth = 0; if ($this->caching) { // save old cache_info, initialize cache_info array_push($_cache_info, $this->_cache_info); $this->_cache_info = array(); $_params = array('tpl_file' => $resource_name , 'cache_id' => $cache_id , 'compile_id' => $compile_id , 'results' => null); require_once (SMARTY_CORE_DIR . 'core.read_cache_file.php'); if (smarty_core_read_cache_file($_params, $this)) { $_smarty_results = $_params['results']; if (! empty($this->_cache_info['insert_tags'])) { $_params = array('plugins' => $this->_cache_info['insert_tags']); require_once (SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins($_params, $this); $_params = array('results' => $_smarty_results); require_once (SMARTY_CORE_DIR . 'core.process_cached_inserts.php'); $_smarty_results = smarty_core_process_cached_inserts($_params, $this); } if (! empty($this->_cache_info['cache_serials'])) { $_params = array('results' => $_smarty_results); require_once (SMARTY_CORE_DIR . 'core.process_compiled_include.php'); $_smarty_results = smarty_core_process_compiled_include($_params, $this); } if ($display) { if ($this->debugging) { // capture time for debugging info $_params = array(); require_once (SMARTY_CORE_DIR . 'core.get_microtime.php'); $this->_smarty_debug_info[$_included_tpls_idx]['exec_time'] = smarty_core_get_microtime($_params, $this) - $_debug_start_time; require_once (SMARTY_CORE_DIR . 'core.display_debug_console.php'); $_smarty_results .= smarty_core_display_debug_console($_params, $this); } if ($this->cache_modified_check) { $_server_vars = ($this->request_use_auto_globals) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS']; $_last_modified_date = @substr($_server_vars['HTTP_IF_MODIFIED_SINCE'], 0, strpos($_server_vars['HTTP_IF_MODIFIED_SINCE'], 'GMT') + 3); $_gmt_mtime = gmdate('D, d M Y H:i:s', $this->_cache_info['timestamp']) . ' GMT'; if (@count($this->_cache_info['insert_tags']) == 0 && ! $this->_cache_serials && $_gmt_mtime == $_last_modified_date) { if (php_sapi_name() == 'cgi') header('Status: 304 Not Modified'); else header('HTTP/1.1 304 Not Modified'); } else { header('Last-Modified: ' . $_gmt_mtime); echo $_smarty_results; } } else { echo $_smarty_results; } error_reporting($_smarty_old_error_level); // restore initial cache_info $this->_cache_info = array_pop($_cache_info); return true; } else { error_reporting($_smarty_old_error_level); // restore initial cache_info $this->_cache_info = array_pop($_cache_info); return $_smarty_results; } } else { $this->_cache_info['template'][$resource_name] = true; if ($this->cache_modified_check && $display) { header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT'); } } } // load filters that are marked as autoload if (count($this->autoload_filters)) { foreach ($this->autoload_filters as $_filter_type => $_filters) { foreach ($_filters as $_filter) { $this->load_filter($_filter_type, $_filter); } } } $_smarty_compile_path = $this->_get_compile_path($resource_name); // if we just need to display the results, don't perform output // buffering - for speed $_cache_including = $this->_cache_including; $this->_cache_including = false; if ($display && ! $this->caching && count($this->_plugins['outputfilter']) == 0) { if ($this->_is_compiled($resource_name, $_smarty_compile_path) || $this->_compile_resource($resource_name, $_smarty_compile_path)) { include ($_smarty_compile_path); } } else { ob_start(); if ($this->_is_compiled($resource_name, $_smarty_compile_path) || $this->_compile_resource($resource_name, $_smarty_compile_path)) { include ($_smarty_compile_path); } $_smarty_results = ob_get_contents(); ob_end_clean(); foreach ((array) $this->_plugins['outputfilter'] as $_output_filter) { $_smarty_results = call_user_func_array($_output_filter[0], array($_smarty_results , &$this)); } } if ($this->caching) { $_params = array('tpl_file' => $resource_name , 'cache_id' => $cache_id , 'compile_id' => $compile_id , 'results' => $_smarty_results); require_once (SMARTY_CORE_DIR . 'core.write_cache_file.php'); smarty_core_write_cache_file($_params, $this); require_once (SMARTY_CORE_DIR . 'core.process_cached_inserts.php'); $_smarty_results = smarty_core_process_cached_inserts($_params, $this); if ($this->_cache_serials) { // strip nocache-tags from output $_smarty_results = preg_replace('!(\{/?nocache\:[0-9a-f]{32}#\d+\})!s', '', $_smarty_results); } // restore initial cache_info $this->_cache_info = array_pop($_cache_info); } $this->_cache_including = $_cache_including; if ($display) { if (isset($_smarty_results)) { echo $_smarty_results; } if ($this->debugging) { // capture time for debugging info $_params = array(); require_once (SMARTY_CORE_DIR . 'core.get_microtime.php'); $this->_smarty_debug_info[$_included_tpls_idx]['exec_time'] = (smarty_core_get_microtime($_params, $this) - $_debug_start_time); require_once (SMARTY_CORE_DIR . 'core.display_debug_console.php'); echo smarty_core_display_debug_console($_params, $this); } error_reporting($_smarty_old_error_level); return; } else { error_reporting($_smarty_old_error_level); if (isset($_smarty_results)) { return $_smarty_results; } } } /** * load configuration values * * @param string $file * @param string $section * @param string $scope */ function config_load ($file, $section = null, $scope = 'global') { require_once ($this->_get_plugin_filepath('function', 'config_load')); smarty_function_config_load(array('file' => $file , 'section' => $section , 'scope' => $scope), $this); } /** * return a reference to a registered object * * @param string $name * @return object */ function &get_registered_object ($name) { if (! isset($this->_reg_objects[$name])) $this->_trigger_fatal_error("'$name' is not a registered object"); if (! is_object($this->_reg_objects[$name][0])) $this->_trigger_fatal_error("registered '$name' is not an object"); return $this->_reg_objects[$name][0]; } /** * clear configuration values * * @param string $var */ function clear_config ($var = null) { if (! isset($var)) { // clear all values $this->_config = array(array('vars' => array() , 'files' => array())); } else { unset($this->_config[0]['vars'][$var]); } } /** * get filepath of requested plugin * * @param string $type * @param string $name * @return string|false */ function _get_plugin_filepath ($type, $name) { $_params = array('type' => $type , 'name' => $name); require_once (SMARTY_CORE_DIR . 'core.assemble_plugin_filepath.php'); return smarty_core_assemble_plugin_filepath($_params, $this); } /** * test if resource needs compiling * * @param string $resource_name * @param string $compile_path * @return boolean */ function _is_compiled ($resource_name, $compile_path) { if (! $this->force_compile && file_exists($compile_path)) { if (! $this->compile_check) { // no need to check compiled file return true; } else { // get file source and timestamp $_params = array('resource_name' => $resource_name , 'get_source' => false); if (! $this->_fetch_resource_info($_params)) { return false; } if ($_params['resource_timestamp'] <= filemtime($compile_path)) { // template not expired, no recompile return true; } else { // compile template return false; } } } else { // compiled template does not exist, or forced compile return false; } } /** * compile the template * * @param string $resource_name * @param string $compile_path * @return boolean */ function _compile_resource ($resource_name, $compile_path) { $_params = array('resource_name' => $resource_name); if (! $this->_fetch_resource_info($_params)) { return false; } $_source_content = $_params['source_content']; $_cache_include = substr($compile_path, 0, - 4) . '.inc'; if ($this->_compile_source($resource_name, $_source_content, $_compiled_content, $_cache_include)) { // if a _cache_serial was set, we also have to write an include-file: if ($this->_cache_include_info) { require_once (SMARTY_CORE_DIR . 'core.write_compiled_include.php'); smarty_core_write_compiled_include(array_merge($this->_cache_include_info, array('compiled_content' => $_compiled_content , 'resource_name' => $resource_name)), $this); } $_params = array('compile_path' => $compile_path , 'compiled_content' => $_compiled_content); require_once (SMARTY_CORE_DIR . 'core.write_compiled_resource.php'); smarty_core_write_compiled_resource($_params, $this); return true; } else { return false; } } /** * compile the given source * * @param string $resource_name * @param string $source_content * @param string $compiled_content * @return boolean */ function _compile_source ($resource_name, &$source_content, &$compiled_content, $cache_include_path = null) { if (file_exists(SMARTY_DIR . $this->compiler_file)) { require_once (SMARTY_DIR . $this->compiler_file); } else { // use include_path require_once ($this->compiler_file); } $smarty_compiler = new $this->compiler_class(); $smarty_compiler->template_dir = $this->template_dir; $smarty_compiler->compile_dir = $this->compile_dir; $smarty_compiler->plugins_dir = $this->plugins_dir; $smarty_compiler->config_dir = $this->config_dir; $smarty_compiler->force_compile = $this->force_compile; $smarty_compiler->caching = $this->caching; $smarty_compiler->php_handling = $this->php_handling; $smarty_compiler->left_delimiter = $this->left_delimiter; $smarty_compiler->right_delimiter = $this->right_delimiter; $smarty_compiler->_version = $this->_version; $smarty_compiler->security = $this->security; $smarty_compiler->secure_dir = $this->secure_dir; $smarty_compiler->security_settings = $this->security_settings; $smarty_compiler->trusted_dir = $this->trusted_dir; $smarty_compiler->use_sub_dirs = $this->use_sub_dirs; $smarty_compiler->_reg_objects = &$this->_reg_objects; $smarty_compiler->_plugins = &$this->_plugins; $smarty_compiler->_tpl_vars = &$this->_tpl_vars; $smarty_compiler->default_modifiers = $this->default_modifiers; $smarty_compiler->compile_id = $this->_compile_id; $smarty_compiler->_config = $this->_config; $smarty_compiler->request_use_auto_globals = $this->request_use_auto_globals; if (isset($cache_include_path) && isset($this->_cache_serials[$cache_include_path])) { $smarty_compiler->_cache_serial = $this->_cache_serials[$cache_include_path]; } $smarty_compiler->_cache_include = $cache_include_path; $_results = $smarty_compiler->_compile_file($resource_name, $source_content, $compiled_content); if ($smarty_compiler->_cache_serial) { $this->_cache_include_info = array('cache_serial' => $smarty_compiler->_cache_serial , 'plugins_code' => $smarty_compiler->_plugins_code , 'include_file_path' => $cache_include_path); } else { $this->_cache_include_info = null; } return $_results; } /** * Get the compile path for this resource * * @param string $resource_name * @return string results of {@link _get_auto_filename()} */ function _get_compile_path ($resource_name) { return $this->_get_auto_filename($this->compile_dir, $resource_name, $this->_compile_id) . '.php'; } /** * fetch the template info. Gets timestamp, and source * if get_source is true * * sets $source_content to the source of the template, and * $resource_timestamp to its time stamp * @param string $resource_name * @param string $source_content * @param integer $resource_timestamp * @param boolean $get_source * @param boolean $quiet * @return boolean */ function _fetch_resource_info (&$params) { if (! isset($params['get_source'])) { $params['get_source'] = true; } if (! isset($params['quiet'])) { $params['quiet'] = false; } $_return = false; $_params = array('resource_name' => $params['resource_name']); if (isset($params['resource_base_path'])) $_params['resource_base_path'] = $params['resource_base_path']; else $_params['resource_base_path'] = $this->template_dir; if ($this->_parse_resource_name($_params)) { $_resource_type = $_params['resource_type']; $_resource_name = $_params['resource_name']; switch ($_resource_type) { case 'file' : if ($params['get_source']) { $params['source_content'] = $this->_read_file($_resource_name); } $params['resource_timestamp'] = filemtime($_resource_name); $_return = is_file($_resource_name); break; default: // call resource functions to fetch the template source and timestamp if ($params['get_source']) { $_source_return = isset($this->_plugins['resource'][$_resource_type]) && call_user_func_array($this->_plugins['resource'][$_resource_type][0][0], array($_resource_name , &$params['source_content'] , &$this)); } else { $_source_return = true; } $_timestamp_return = isset($this->_plugins['resource'][$_resource_type]) && call_user_func_array($this->_plugins['resource'][$_resource_type][0][1], array($_resource_name , &$params['resource_timestamp'] , &$this)); $_return = $_source_return && $_timestamp_return; break; } } if (! $_return) { // see if we can get a template with the default template handler if (! empty($this->default_template_handler_func)) { if (! is_callable($this->default_template_handler_func)) { $this->trigger_error("default template handler function \"$this->default_template_handler_func\" doesn't exist."); } else { $_return = call_user_func_array($this->default_template_handler_func, array($_params['resource_type'] , $_params['resource_name'] , &$params['source_content'] , &$params['resource_timestamp'] , &$this)); } } } if (! $_return) { if (! $params['quiet']) { $this->trigger_error('unable to read resource: "' . $params['resource_name'] . '"'); } } else if ($_return && $this->security) { require_once (SMARTY_CORE_DIR . 'core.is_secure.php'); if (! smarty_core_is_secure($_params, $this)) { if (! $params['quiet']) $this->trigger_error('(secure mode) accessing "' . $params['resource_name'] . '" is not allowed'); $params['source_content'] = null; $params['resource_timestamp'] = null; return false; } } return $_return; } /** * parse out the type and name from the resource * * @param string $resource_base_path * @param string $resource_name * @param string $resource_type * @param string $resource_name * @return boolean */ function _parse_resource_name (&$params) { // split tpl_path by the first colon $_resource_name_parts = explode(':', $params['resource_name'], 2); if (count($_resource_name_parts) == 1) { // no resource type given $params['resource_type'] = $this->default_resource_type; $params['resource_name'] = $_resource_name_parts[0]; } else { if (strlen($_resource_name_parts[0]) == 1) { // 1 char is not resource type, but part of filepath $params['resource_type'] = $this->default_resource_type; $params['resource_name'] = $params['resource_name']; } else { $params['resource_type'] = $_resource_name_parts[0]; $params['resource_name'] = $_resource_name_parts[1]; } } if ($params['resource_type'] == 'file') { if (! preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $params['resource_name'])) { // relative pathname to $params['resource_base_path'] // use the first directory where the file is found foreach ((array) $params['resource_base_path'] as $_curr_path) { $_fullpath = $_curr_path . DIRECTORY_SEPARATOR . $params['resource_name']; if (file_exists($_fullpath) && is_file($_fullpath)) { $params['resource_name'] = $_fullpath; return true; } // didn't find the file, try include_path $_params = array('file_path' => $_fullpath); require_once (SMARTY_CORE_DIR . 'core.get_include_path.php'); if (smarty_core_get_include_path($_params, $this)) { $params['resource_name'] = $_params['new_file_path']; return true; } } return false; } else { /* absolute path */ return file_exists($params['resource_name']); } } elseif (empty($this->_plugins['resource'][$params['resource_type']])) { $_params = array('type' => $params['resource_type']); require_once (SMARTY_CORE_DIR . 'core.load_resource_plugin.php'); smarty_core_load_resource_plugin($_params, $this); } return true; } /** * Handle modifiers * * @param string|null $modifier_name * @param array|null $map_array * @return string result of modifiers */ function _run_mod_handler () { $_args = func_get_args(); list ($_modifier_name, $_map_array) = array_splice($_args, 0, 2); list ($_func_name, $_tpl_file, $_tpl_line) = $this->_plugins['modifier'][$_modifier_name]; $_var = $_args[0]; foreach ($_var as $_key => $_val) { $_args[0] = $_val; $_var[$_key] = call_user_func_array($_func_name, $_args); } return $_var; } /** * Remove starting and ending quotes from the string * * @param string $string * @return string */ function _dequote ($string) { if ((substr($string, 0, 1) == "'" || substr($string, 0, 1) == '"') && substr($string, - 1) == substr($string, 0, 1)) return substr($string, 1, - 1); else return $string; } /** * read in a file * * @param string $filename * @return string */ function _read_file ($filename) { if (file_exists($filename) && ($fd = @fopen($filename, 'rb'))) { $contents = ''; while (! feof($fd)) { $contents .= fread($fd, 8192); } fclose($fd); return $contents; } else { return false; } } /** * get a concrete filename for automagically created content * * @param string $auto_base * @param string $auto_source * @param string $auto_id * @return string * @staticvar string|null * @staticvar string|null */ function _get_auto_filename ($auto_base, $auto_source = null, $auto_id = null) { $_compile_dir_sep = $this->use_sub_dirs ? DIRECTORY_SEPARATOR : '^'; $_return = $auto_base . DIRECTORY_SEPARATOR; if (isset($auto_id)) { // make auto_id safe for directory names $auto_id = str_replace('%7C', $_compile_dir_sep, (urlencode($auto_id))); // split into separate directories $_return .= $auto_id . $_compile_dir_sep; } if (isset($auto_source)) { // make source name safe for filename $_filename = urlencode(basename($auto_source)); $_crc32 = sprintf('%08X', crc32($auto_source)); // prepend %% to avoid name conflicts with // with $params['auto_id'] names $_crc32 = substr($_crc32, 0, 2) . $_compile_dir_sep . substr($_crc32, 0, 3) . $_compile_dir_sep . $_crc32; $_return .= '%%' . $_crc32 . '%%' . $_filename; } return $_return; } /** * unlink a file, possibly using expiration time * * @param string $resource * @param integer $exp_time */ function _unlink ($resource, $exp_time = null) { if (isset($exp_time)) { if (time() - @filemtime($resource) >= $exp_time) { return @unlink($resource); } } else { return @unlink($resource); } } /** * returns an auto_id for auto-file-functions * * @param string $cache_id * @param string $compile_id * @return string|null */ function _get_auto_id ($cache_id = null, $compile_id = null) { if (isset($cache_id)) return (isset($compile_id)) ? $cache_id . '|' . $compile_id : $cache_id; elseif (isset($compile_id)) return $compile_id; else return null; } /** * trigger Smarty plugin error * * @param string $error_msg * @param string $tpl_file * @param integer $tpl_line * @param string $file * @param integer $line * @param integer $error_type */ function _trigger_fatal_error ($error_msg, $tpl_file = null, $tpl_line = null, $file = null, $line = null, $error_type = E_USER_ERROR) { if (isset($file) && isset($line)) { $info = ' (' . basename($file) . ", line $line)"; } else { $info = ''; } if (isset($tpl_line) && isset($tpl_file)) { $this->trigger_error('[in ' . $tpl_file . ' line ' . $tpl_line . "]: $error_msg$info", $error_type); } else { $this->trigger_error($error_msg . $info, $error_type); } } /** * callback function for preg_replace, to call a non-cacheable block * @return string */ function _process_compiled_include_callback ($match) { $_func = '_smarty_tplfunc_' . $match[2] . '_' . $match[3]; ob_start(); $_func($this); $_ret = ob_get_contents(); ob_end_clean(); return $_ret; } /** * called for included templates * * @param string $_smarty_include_tpl_file * @param string $_smarty_include_vars */ // $_smarty_include_tpl_file, $_smarty_include_vars function _smarty_include ($params) { if ($this->debugging) { $_params = array(); require_once (SMARTY_CORE_DIR . 'core.get_microtime.php'); $debug_start_time = smarty_core_get_microtime($_params, $this); $this->_smarty_debug_info[] = array('type' => 'template' , 'filename' => $params['smarty_include_tpl_file'] , 'depth' => ++ $this->_inclusion_depth); $included_tpls_idx = count($this->_smarty_debug_info) - 1; } $this->_tpl_vars = array_merge($this->_tpl_vars, $params['smarty_include_vars']); // config vars are treated as local, so push a copy of the // current ones onto the front of the stack array_unshift($this->_config, $this->_config[0]); $_smarty_compile_path = $this->_get_compile_path($params['smarty_include_tpl_file']); if ($this->_is_compiled($params['smarty_include_tpl_file'], $_smarty_compile_path) || $this->_compile_resource($params['smarty_include_tpl_file'], $_smarty_compile_path)) { include ($_smarty_compile_path); } // pop the local vars off the front of the stack array_shift($this->_config); $this->_inclusion_depth --; if ($this->debugging) { // capture time for debugging info $_params = array(); require_once (SMARTY_CORE_DIR . 'core.get_microtime.php'); $this->_smarty_debug_info[$included_tpls_idx]['exec_time'] = smarty_core_get_microtime($_params, $this) - $debug_start_time; } if ($this->caching) { $this->_cache_info['template'][$params['smarty_include_tpl_file']] = true; } } /** * get or set an array of cached attributes for function that is * not cacheable * @return array */ function &_smarty_cache_attrs ($cache_serial, $count) { $_cache_attrs = & $this->_cache_info['cache_attrs'][$cache_serial][$count]; if ($this->_cache_including) { /* return next set of cache_attrs */ $_return = current($_cache_attrs); next($_cache_attrs); return $_return; } else { /* add a reference to a new set of cache_attrs */ $_cache_attrs[] = array(); return $_cache_attrs[count($_cache_attrs) - 1]; } } /** * wrapper for include() retaining $this * @return mixed */ function _include ($filename, $once = false, $params = null) { if ($once) { return include_once ($filename); } else { return include ($filename); } } /** * wrapper for eval() retaining $this * @return mixed */ function _eval ($code, $params = null) { return eval($code); } /** * Extracts the filter name from the given callback * * @param callback $function * @return string */ function _get_filter_name ($function) { if (is_array($function)) { $_class_name = (is_object($function[0]) ? get_class($function[0]) : $function[0]); return $_class_name . '_' . $function[1]; } else { return $function; } } /**#@-*/ } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/Smarty.php
PHP
asf20
66,097
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty debug_console function plugin * * Type: core<br> * Name: display_debug_console<br> * Purpose: display the javascript debug console window * @param array Format: null * @param Smarty */ function smarty_core_display_debug_console($params, &$smarty) { // we must force compile the debug template in case the environment // changed between separate applications. if(empty($smarty->debug_tpl)) { // set path to debug template from SMARTY_DIR $smarty->debug_tpl = SMARTY_DIR . 'debug.tpl'; if($smarty->security && is_file($smarty->debug_tpl)) { $smarty->secure_dir[] = realpath($smarty->debug_tpl); } $smarty->debug_tpl = 'file:' . SMARTY_DIR . 'debug.tpl'; } $_ldelim_orig = $smarty->left_delimiter; $_rdelim_orig = $smarty->right_delimiter; $smarty->left_delimiter = '{'; $smarty->right_delimiter = '}'; $_compile_id_orig = $smarty->_compile_id; $smarty->_compile_id = null; $_compile_path = $smarty->_get_compile_path($smarty->debug_tpl); if ($smarty->_compile_resource($smarty->debug_tpl, $_compile_path)) { ob_start(); $smarty->_include($_compile_path); $_results = ob_get_contents(); ob_end_clean(); } else { $_results = ''; } $smarty->_compile_id = $_compile_id_orig; $smarty->left_delimiter = $_ldelim_orig; $smarty->right_delimiter = $_rdelim_orig; return $_results; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.display_debug_console.php
PHP
asf20
1,583
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * create full directory structure * * @param string $dir */ // $dir function smarty_core_create_dir_structure($params, &$smarty) { if (!file_exists($params['dir'])) { $_open_basedir_ini = ini_get('open_basedir'); if (DIRECTORY_SEPARATOR=='/') { /* unix-style paths */ $_dir = $params['dir']; $_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY); $_new_dir = (substr($_dir, 0, 1)=='/') ? '/' : getcwd().'/'; if($_use_open_basedir = !empty($_open_basedir_ini)) { $_open_basedirs = explode(':', $_open_basedir_ini); } } else { /* other-style paths */ $_dir = str_replace('\\','/', $params['dir']); $_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY); if (preg_match('!^((//)|([a-zA-Z]:/))!', $_dir, $_root_dir)) { /* leading "//" for network volume, or "[letter]:/" for full path */ $_new_dir = $_root_dir[1]; /* remove drive-letter from _dir_parts */ if (isset($_root_dir[3])) array_shift($_dir_parts); } else { $_new_dir = str_replace('\\', '/', getcwd()).'/'; } if($_use_open_basedir = !empty($_open_basedir_ini)) { $_open_basedirs = explode(';', str_replace('\\', '/', $_open_basedir_ini)); } } /* all paths use "/" only from here */ foreach ($_dir_parts as $_dir_part) { $_new_dir .= $_dir_part; if ($_use_open_basedir) { // do not attempt to test or make directories outside of open_basedir $_make_new_dir = false; foreach ($_open_basedirs as $_open_basedir) { if (substr($_new_dir, 0, strlen($_open_basedir)) == $_open_basedir) { $_make_new_dir = true; break; } } } else { $_make_new_dir = true; } if ($_make_new_dir && !file_exists($_new_dir) && !@mkdir($_new_dir, $smarty->_dir_perms) && !is_dir($_new_dir)) { $smarty->trigger_error("problem creating directory '" . $_new_dir . "'"); return false; } $_new_dir .= '/'; } } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.create_dir_structure.php
PHP
asf20
2,507
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * determines if a resource is trusted or not * * @param string $resource_type * @param string $resource_name * @return boolean */ // $resource_type, $resource_name function smarty_core_is_trusted($params, &$smarty) { $_smarty_trusted = false; if ($params['resource_type'] == 'file') { if (!empty($smarty->trusted_dir)) { $_rp = realpath($params['resource_name']); foreach ((array)$smarty->trusted_dir as $curr_dir) { if (!empty($curr_dir) && is_readable ($curr_dir)) { $_cd = realpath($curr_dir); if (strncmp($_rp, $_cd, strlen($_cd)) == 0 && substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR ) { $_smarty_trusted = true; break; } } } } } else { // resource is not on local file system $_smarty_trusted = call_user_func_array($smarty->_plugins['resource'][$params['resource_type']][0][3], array($params['resource_name'], $smarty)); } return $_smarty_trusted; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.is_trusted.php
PHP
asf20
1,284
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Extract non-cacheable parts out of compiled template and write it * * @param string $compile_path * @param string $template_compiled * @return boolean */ function smarty_core_write_compiled_include($params, &$smarty) { $_tag_start = 'if \(\$this->caching && \!\$this->_cache_including\)\: echo \'\{nocache\:('.$params['cache_serial'].')#(\d+)\}\'; endif;'; $_tag_end = 'if \(\$this->caching && \!\$this->_cache_including\)\: echo \'\{/nocache\:(\\2)#(\\3)\}\'; endif;'; preg_match_all('!('.$_tag_start.'(.*)'.$_tag_end.')!Us', $params['compiled_content'], $_match_source, PREG_SET_ORDER); // no nocache-parts found: done if (count($_match_source)==0) return; // convert the matched php-code to functions $_include_compiled = "<?php /* Smarty version ".$smarty->_version.", created on ".strftime("%Y-%m-%d %H:%M:%S")."\n"; $_include_compiled .= " compiled from " . strtr(urlencode($params['resource_name']), array('%2F'=>'/', '%3A'=>':')) . " */\n\n"; $_compile_path = $params['include_file_path']; $smarty->_cache_serials[$_compile_path] = $params['cache_serial']; $_include_compiled .= "\$this->_cache_serials['".$_compile_path."'] = '".$params['cache_serial']."';\n\n?>"; $_include_compiled .= $params['plugins_code']; $_include_compiled .= "<?php"; $this_varname = ((double)phpversion() >= 5.0) ? '_smarty' : 'this'; for ($_i = 0, $_for_max = count($_match_source); $_i < $_for_max; $_i++) { $_match =& $_match_source[$_i]; $source = $_match[4]; if ($this_varname == '_smarty') { /* rename $this to $_smarty in the sourcecode */ $tokens = token_get_all('<?php ' . $_match[4]); /* remove trailing <?php */ $open_tag = ''; while ($tokens) { $token = array_shift($tokens); if (is_array($token)) { $open_tag .= $token[1]; } else { $open_tag .= $token; } if ($open_tag == '<?php ') break; } for ($i=0, $count = count($tokens); $i < $count; $i++) { if (is_array($tokens[$i])) { if ($tokens[$i][0] == T_VARIABLE && $tokens[$i][1] == '$this') { $tokens[$i] = '$' . $this_varname; } else { $tokens[$i] = $tokens[$i][1]; } } } $source = implode('', $tokens); } /* add function to compiled include */ $_include_compiled .= " function _smarty_tplfunc_$_match[2]_$_match[3](&\$$this_varname) { $source } "; } $_include_compiled .= "\n\n?>"; $_params = array('filename' => $_compile_path, 'contents' => $_include_compiled, 'create_dirs' => true); require_once(SMARTY_CORE_DIR . 'core.write_file.php'); smarty_core_write_file($_params, $smarty); return true; } ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.write_compiled_include.php
PHP
asf20
3,219
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * load a resource plugin * * @param string $type */ // $type function smarty_core_load_resource_plugin($params, &$smarty) { /* * Resource plugins are not quite like the other ones, so they are * handled differently. The first element of plugin info is the array of * functions provided by the plugin, the second one indicates whether * all of them exist or not. */ $_plugin = &$smarty->_plugins['resource'][$params['type']]; if (isset($_plugin)) { if (!$_plugin[1] && count($_plugin[0])) { $_plugin[1] = true; foreach ($_plugin[0] as $_plugin_func) { if (!is_callable($_plugin_func)) { $_plugin[1] = false; break; } } } if (!$_plugin[1]) { $smarty->_trigger_fatal_error("[plugin] resource '" . $params['type'] . "' is not implemented", null, null, __FILE__, __LINE__); } return; } $_plugin_file = $smarty->_get_plugin_filepath('resource', $params['type']); $_found = ($_plugin_file != false); if ($_found) { /* * If the plugin file is found, it -must- provide the properly named * plugin functions. */ include_once($_plugin_file); /* * Locate functions that we require the plugin to provide. */ $_resource_ops = array('source', 'timestamp', 'secure', 'trusted'); $_resource_funcs = array(); foreach ($_resource_ops as $_op) { $_plugin_func = 'smarty_resource_' . $params['type'] . '_' . $_op; if (!function_exists($_plugin_func)) { $smarty->_trigger_fatal_error("[plugin] function $_plugin_func() not found in $_plugin_file", null, null, __FILE__, __LINE__); return; } else { $_resource_funcs[] = $_plugin_func; } } $smarty->_plugins['resource'][$params['type']] = array($_resource_funcs, true); } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.load_resource_plugin.php
PHP
asf20
2,147
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * delete a dir recursively (level=0 -> keep root) * WARNING: no tests, it will try to remove what you tell it! * * @param string $dirname * @param integer $level * @param integer $exp_time * @return boolean */ // $dirname, $level = 1, $exp_time = null function smarty_core_rmdir($params, &$smarty) { if(!isset($params['level'])) { $params['level'] = 1; } if(!isset($params['exp_time'])) { $params['exp_time'] = null; } if($_handle = @opendir($params['dirname'])) { while (false !== ($_entry = readdir($_handle))) { if ($_entry != '.' && $_entry != '..') { if (@is_dir($params['dirname'] . DIRECTORY_SEPARATOR . $_entry)) { $_params = array( 'dirname' => $params['dirname'] . DIRECTORY_SEPARATOR . $_entry, 'level' => $params['level'] + 1, 'exp_time' => $params['exp_time'] ); smarty_core_rmdir($_params, $smarty); } else { $smarty->_unlink($params['dirname'] . DIRECTORY_SEPARATOR . $_entry, $params['exp_time']); } } } closedir($_handle); } if ($params['level']) { return @rmdir($params['dirname']); } return (bool)$_handle; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.rmdir.php
PHP
asf20
1,498
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Retrieves PHP script resource * * sets $php_resource to the returned resource * @param string $resource * @param string $resource_type * @param $php_resource * @return boolean */ function smarty_core_get_php_resource(&$params, &$smarty) { $params['resource_base_path'] = $smarty->trusted_dir; $smarty->_parse_resource_name($params, $smarty); /* * Find out if the resource exists. */ if ($params['resource_type'] == 'file') { $_readable = false; if(file_exists($params['resource_name']) && is_readable($params['resource_name'])) { $_readable = true; } else { // test for file in include_path $_params = array('file_path' => $params['resource_name']); require_once(SMARTY_CORE_DIR . 'core.get_include_path.php'); if(smarty_core_get_include_path($_params, $smarty)) { $_include_path = $_params['new_file_path']; $_readable = true; } } } else if ($params['resource_type'] != 'file') { $_template_source = null; $_readable = is_callable($smarty->_plugins['resource'][$params['resource_type']][0][0]) && call_user_func_array($smarty->_plugins['resource'][$params['resource_type']][0][0], array($params['resource_name'], &$_template_source, &$smarty)); } /* * Set the error function, depending on which class calls us. */ if (method_exists($smarty, '_syntax_error')) { $_error_funcc = '_syntax_error'; } else { $_error_funcc = 'trigger_error'; } if ($_readable) { if ($smarty->security) { require_once(SMARTY_CORE_DIR . 'core.is_trusted.php'); if (!smarty_core_is_trusted($params, $smarty)) { $smarty->$_error_funcc('(secure mode) ' . $params['resource_type'] . ':' . $params['resource_name'] . ' is not trusted'); return false; } } } else { $smarty->$_error_funcc($params['resource_type'] . ':' . $params['resource_name'] . ' is not readable'); return false; } if ($params['resource_type'] == 'file') { $params['php_resource'] = $params['resource_name']; } else { $params['php_resource'] = $_template_source; } return true; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.get_php_resource.php
PHP
asf20
2,467
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Replace cached inserts with the actual results * * @param string $results * @return string */ function smarty_core_process_cached_inserts($params, &$smarty) { preg_match_all('!'.$smarty->_smarty_md5.'{insert_cache (.*)}'.$smarty->_smarty_md5.'!Uis', $params['results'], $match); list($cached_inserts, $insert_args) = $match; for ($i = 0, $for_max = count($cached_inserts); $i < $for_max; $i++) { if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $debug_start_time = smarty_core_get_microtime($_params, $smarty); } $args = unserialize($insert_args[$i]); $name = $args['name']; if (isset($args['script'])) { $_params = array('resource_name' => $smarty->_dequote($args['script'])); require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php'); if(!smarty_core_get_php_resource($_params, $smarty)) { return false; } $resource_type = $_params['resource_type']; $php_resource = $_params['php_resource']; if ($resource_type == 'file') { $smarty->_include($php_resource, true); } else { $smarty->_eval($php_resource); } } $function_name = $smarty->_plugins['insert'][$name][0]; if (empty($args['assign'])) { $replace = $function_name($args, $smarty); } else { $smarty->assign($args['assign'], $function_name($args, $smarty)); $replace = ''; } $params['results'] = substr_replace($params['results'], $replace, strpos($params['results'], $cached_inserts[$i]), strlen($cached_inserts[$i])); if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $smarty->_smarty_debug_info[] = array('type' => 'insert', 'filename' => 'insert_'.$name, 'depth' => $smarty->_inclusion_depth, 'exec_time' => smarty_core_get_microtime($_params, $smarty) - $debug_start_time); } } return $params['results']; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.process_cached_inserts.php
PHP
asf20
2,464
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * called for included php files within templates * * @param string $smarty_file * @param string $smarty_assign variable to assign the included template's * output into * @param boolean $smarty_once uses include_once if this is true * @param array $smarty_include_vars associative array of vars from * {include file="blah" var=$var} */ // $file, $assign, $once, $_smarty_include_vars function smarty_core_smarty_include_php($params, &$smarty) { $_params = array('resource_name' => $params['smarty_file']); require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php'); smarty_core_get_php_resource($_params, $smarty); $_smarty_resource_type = $_params['resource_type']; $_smarty_php_resource = $_params['php_resource']; if (!empty($params['smarty_assign'])) { ob_start(); if ($_smarty_resource_type == 'file') { $smarty->_include($_smarty_php_resource, $params['smarty_once'], $params['smarty_include_vars']); } else { $smarty->_eval($_smarty_php_resource, $params['smarty_include_vars']); } $smarty->assign($params['smarty_assign'], ob_get_contents()); ob_end_clean(); } else { if ($_smarty_resource_type == 'file') { $smarty->_include($_smarty_php_resource, $params['smarty_once'], $params['smarty_include_vars']); } else { $smarty->_eval($_smarty_php_resource, $params['smarty_include_vars']); } } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.smarty_include_php.php
PHP
asf20
1,602
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * delete an automagically created file by name and id * * @param string $auto_base * @param string $auto_source * @param string $auto_id * @param integer $exp_time * @return boolean */ // $auto_base, $auto_source = null, $auto_id = null, $exp_time = null function smarty_core_rm_auto($params, &$smarty) { if (!@is_dir($params['auto_base'])) return false; if(!isset($params['auto_id']) && !isset($params['auto_source'])) { $_params = array( 'dirname' => $params['auto_base'], 'level' => 0, 'exp_time' => $params['exp_time'] ); require_once(SMARTY_CORE_DIR . 'core.rmdir.php'); $_res = smarty_core_rmdir($_params, $smarty); } else { $_tname = $smarty->_get_auto_filename($params['auto_base'], $params['auto_source'], $params['auto_id']); if(isset($params['auto_source'])) { if (isset($params['extensions'])) { $_res = false; foreach ((array)$params['extensions'] as $_extension) $_res |= $smarty->_unlink($_tname.$_extension, $params['exp_time']); } else { $_res = $smarty->_unlink($_tname, $params['exp_time']); } } elseif ($smarty->use_sub_dirs) { $_params = array( 'dirname' => $_tname, 'level' => 1, 'exp_time' => $params['exp_time'] ); require_once(SMARTY_CORE_DIR . 'core.rmdir.php'); $_res = smarty_core_rmdir($_params, $smarty); } else { // remove matching file names $_handle = opendir($params['auto_base']); $_res = true; while (false !== ($_filename = readdir($_handle))) { if($_filename == '.' || $_filename == '..') { continue; } elseif (substr($params['auto_base'] . DIRECTORY_SEPARATOR . $_filename, 0, strlen($_tname)) == $_tname) { $_res &= (bool)$smarty->_unlink($params['auto_base'] . DIRECTORY_SEPARATOR . $_filename, $params['exp_time']); } } } } return $_res; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.rm_auto.php
PHP
asf20
2,357
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * assemble filepath of requested plugin * * @param string $type * @param string $name * @return string|false */ function smarty_core_assemble_plugin_filepath($params, &$smarty) { static $_filepaths_cache = array(); $_plugin_filename = $params['type'] . '.' . $params['name'] . '.php'; if (isset($_filepaths_cache[$_plugin_filename])) { return $_filepaths_cache[$_plugin_filename]; } $_return = false; foreach ((array)$smarty->plugins_dir as $_plugin_dir) { $_plugin_filepath = $_plugin_dir . DIRECTORY_SEPARATOR . $_plugin_filename; // see if path is relative if (!preg_match("/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/", $_plugin_dir)) { $_relative_paths[] = $_plugin_dir; // relative path, see if it is in the SMARTY_DIR if (@is_readable(SMARTY_DIR . $_plugin_filepath)) { $_return = SMARTY_DIR . $_plugin_filepath; break; } } // try relative to cwd (or absolute) if (@is_readable($_plugin_filepath)) { $_return = $_plugin_filepath; break; } } if($_return === false) { // still not found, try PHP include_path if(isset($_relative_paths)) { foreach ((array)$_relative_paths as $_plugin_dir) { $_plugin_filepath = $_plugin_dir . DIRECTORY_SEPARATOR . $_plugin_filename; $_params = array('file_path' => $_plugin_filepath); require_once(SMARTY_CORE_DIR . 'core.get_include_path.php'); if(smarty_core_get_include_path($_params, $smarty)) { $_return = $_params['new_file_path']; break; } } } } $_filepaths_cache[$_plugin_filename] = $_return; return $_return; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.assemble_plugin_filepath.php
PHP
asf20
1,949
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * write out a file to disk * * @param string $filename * @param string $contents * @param boolean $create_dirs * @return boolean */ function smarty_core_write_file($params, &$smarty) { $_dirname = dirname($params['filename']); if ($params['create_dirs']) { $_params = array('dir' => $_dirname); require_once(SMARTY_CORE_DIR . 'core.create_dir_structure.php'); smarty_core_create_dir_structure($_params, $smarty); } // write to tmp file, then rename it to avoid file locking race condition $_tmp_file = tempnam($_dirname, 'wrt'); if (!($fd = @fopen($_tmp_file, 'wb'))) { $_tmp_file = $_dirname . DIRECTORY_SEPARATOR . uniqid('wrt'); if (!($fd = @fopen($_tmp_file, 'wb'))) { $smarty->trigger_error("problem writing temporary file '$_tmp_file'"); return false; } } fwrite($fd, $params['contents']); fclose($fd); if (DIRECTORY_SEPARATOR == '\\' || !@rename($_tmp_file, $params['filename'])) { // On platforms and filesystems that cannot overwrite with rename() // delete the file before renaming it -- because windows always suffers // this, it is short-circuited to avoid the initial rename() attempt @unlink($params['filename']); @rename($_tmp_file, $params['filename']); } @chmod($params['filename'], $smarty->_file_perms); return true; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.write_file.php
PHP
asf20
1,577
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Get path to file from include_path * * @param string $file_path * @param string $new_file_path * @return boolean * @staticvar array|null */ // $file_path, &$new_file_path function smarty_core_get_include_path(&$params, &$smarty) { static $_path_array = null; if(!isset($_path_array)) { $_ini_include_path = ini_get('include_path'); if(strstr($_ini_include_path,';')) { // windows pathnames $_path_array = explode(';',$_ini_include_path); } else { $_path_array = explode(':',$_ini_include_path); } } foreach ($_path_array as $_include_path) { if (@is_readable($_include_path . DIRECTORY_SEPARATOR . $params['file_path'])) { $params['new_file_path'] = $_include_path . DIRECTORY_SEPARATOR . $params['file_path']; return true; } } return false; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.get_include_path.php
PHP
asf20
1,002
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Replace nocache-tags by results of the corresponding non-cacheable * functions and return it * * @param string $compiled_tpl * @param string $cached_source * @return string */ function smarty_core_process_compiled_include($params, &$smarty) { $_cache_including = $smarty->_cache_including; $smarty->_cache_including = true; $_return = $params['results']; foreach ($smarty->_cache_info['cache_serials'] as $_include_file_path=>$_cache_serial) { $smarty->_include($_include_file_path, true); } foreach ($smarty->_cache_info['cache_serials'] as $_include_file_path=>$_cache_serial) { $_return = preg_replace_callback('!(\{nocache\:('.$_cache_serial.')#(\d+)\})!s', array(&$smarty, '_process_compiled_include_callback'), $_return); } $smarty->_cache_including = $_cache_including; return $_return; } ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.process_compiled_include.php
PHP
asf20
1,025
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Get seconds and microseconds * @return double */ function smarty_core_get_microtime($params, &$smarty) { $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = (double)($mtime[1]) + (double)($mtime[0]); return ($mtime); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.get_microtime.php
PHP
asf20
360
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty assign_smarty_interface core plugin * * Type: core<br> * Name: assign_smarty_interface<br> * Purpose: assign the $smarty interface variable * @param array Format: null * @param Smarty */ function smarty_core_assign_smarty_interface($params, &$smarty) { if (isset($smarty->_smarty_vars) && isset($smarty->_smarty_vars['request'])) { return; } $_globals_map = array('g' => 'HTTP_GET_VARS', 'p' => 'HTTP_POST_VARS', 'c' => 'HTTP_COOKIE_VARS', 's' => 'HTTP_SERVER_VARS', 'e' => 'HTTP_ENV_VARS'); $_smarty_vars_request = array(); foreach (preg_split('!!', strtolower($smarty->request_vars_order)) as $_c) { if (isset($_globals_map[$_c])) { $_smarty_vars_request = array_merge($_smarty_vars_request, $GLOBALS[$_globals_map[$_c]]); } } $_smarty_vars_request = @array_merge($_smarty_vars_request, $GLOBALS['HTTP_SESSION_VARS']); $smarty->_smarty_vars['request'] = $_smarty_vars_request; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.assign_smarty_interface.php
PHP
asf20
1,258
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Prepend the cache information to the cache file * and write it * * @param string $tpl_file * @param string $cache_id * @param string $compile_id * @param string $results * @return true|null */ // $tpl_file, $cache_id, $compile_id, $results function smarty_core_write_cache_file($params, &$smarty) { // put timestamp in cache header $smarty->_cache_info['timestamp'] = time(); if ($smarty->cache_lifetime > -1){ // expiration set $smarty->_cache_info['expires'] = $smarty->_cache_info['timestamp'] + $smarty->cache_lifetime; } else { // cache will never expire $smarty->_cache_info['expires'] = -1; } // collapse nocache.../nocache-tags if (preg_match_all('!\{(/?)nocache\:[0-9a-f]{32}#\d+\}!', $params['results'], $match, PREG_PATTERN_ORDER)) { // remove everything between every pair of outermost noache.../nocache-tags // and replace it by a single nocache-tag // this new nocache-tag will be replaced by dynamic contents in // smarty_core_process_compiled_includes() on a cache-read $match_count = count($match[0]); $results = preg_split('!(\{/?nocache\:[0-9a-f]{32}#\d+\})!', $params['results'], -1, PREG_SPLIT_DELIM_CAPTURE); $level = 0; $j = 0; for ($i=0, $results_count = count($results); $i < $results_count && $j < $match_count; $i++) { if ($results[$i] == $match[0][$j]) { // nocache tag if ($match[1][$j]) { // closing tag $level--; unset($results[$i]); } else { // opening tag if ($level++ > 0) unset($results[$i]); } $j++; } elseif ($level > 0) { unset($results[$i]); } } $params['results'] = implode('', $results); } $smarty->_cache_info['cache_serials'] = $smarty->_cache_serials; // prepend the cache header info into cache file $_cache_info = serialize($smarty->_cache_info); $params['results'] = strlen($_cache_info) . "\n" . $_cache_info . $params['results']; if (!empty($smarty->cache_handler_func)) { // use cache_handler function call_user_func_array($smarty->cache_handler_func, array('write', &$smarty, &$params['results'], $params['tpl_file'], $params['cache_id'], $params['compile_id'], $smarty->_cache_info['expires'])); } else { // use local cache file if(!@is_writable($smarty->cache_dir)) { // cache_dir not writable, see if it exists if(!@is_dir($smarty->cache_dir)) { $smarty->trigger_error('the $cache_dir \'' . $smarty->cache_dir . '\' does not exist, or is not a directory.', E_USER_ERROR); return false; } $smarty->trigger_error('unable to write to $cache_dir \'' . realpath($smarty->cache_dir) . '\'. Be sure $cache_dir is writable by the web server user.', E_USER_ERROR); return false; } $_auto_id = $smarty->_get_auto_id($params['cache_id'], $params['compile_id']); $_cache_file = $smarty->_get_auto_filename($smarty->cache_dir, $params['tpl_file'], $_auto_id); $_params = array('filename' => $_cache_file, 'contents' => $params['results'], 'create_dirs' => true); require_once(SMARTY_CORE_DIR . 'core.write_file.php'); smarty_core_write_file($_params, $smarty); return true; } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.write_cache_file.php
PHP
asf20
3,647
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Load requested plugins * * @param array $plugins */ // $plugins function smarty_core_load_plugins($params, &$smarty) { foreach ($params['plugins'] as $_plugin_info) { list($_type, $_name, $_tpl_file, $_tpl_line, $_delayed_loading) = $_plugin_info; $_plugin = &$smarty->_plugins[$_type][$_name]; /* * We do not load plugin more than once for each instance of Smarty. * The following code checks for that. The plugin can also be * registered dynamically at runtime, in which case template file * and line number will be unknown, so we fill them in. * * The final element of the info array is a flag that indicates * whether the dynamically registered plugin function has been * checked for existence yet or not. */ if (isset($_plugin)) { if (empty($_plugin[3])) { if (!is_callable($_plugin[0])) { $smarty->_trigger_fatal_error("[plugin] $_type '$_name' is not implemented", $_tpl_file, $_tpl_line, __FILE__, __LINE__); } else { $_plugin[1] = $_tpl_file; $_plugin[2] = $_tpl_line; $_plugin[3] = true; if (!isset($_plugin[4])) $_plugin[4] = true; /* cacheable */ } } continue; } else if ($_type == 'insert') { /* * For backwards compatibility, we check for insert functions in * the symbol table before trying to load them as a plugin. */ $_plugin_func = 'insert_' . $_name; if (function_exists($_plugin_func)) { $_plugin = array($_plugin_func, $_tpl_file, $_tpl_line, true, false); continue; } } $_plugin_file = $smarty->_get_plugin_filepath($_type, $_name); if (! $_found = ($_plugin_file != false)) { $_message = "could not load plugin file '$_type.$_name.php'\n"; } /* * If plugin file is found, it -must- provide the properly named * plugin function. In case it doesn't, simply output the error and * do not fall back on any other method. */ if ($_found) { include_once $_plugin_file; $_plugin_func = 'smarty_' . $_type . '_' . $_name; if (!function_exists($_plugin_func)) { $smarty->_trigger_fatal_error("[plugin] function $_plugin_func() not found in $_plugin_file", $_tpl_file, $_tpl_line, __FILE__, __LINE__); continue; } } /* * In case of insert plugins, their code may be loaded later via * 'script' attribute. */ else if ($_type == 'insert' && $_delayed_loading) { $_plugin_func = 'smarty_' . $_type . '_' . $_name; $_found = true; } /* * Plugin specific processing and error checking. */ if (!$_found) { if ($_type == 'modifier') { /* * In case modifier falls back on using PHP functions * directly, we only allow those specified in the security * context. */ if ($smarty->security && !in_array($_name, $smarty->security_settings['MODIFIER_FUNCS'])) { $_message = "(secure mode) modifier '$_name' is not allowed"; } else { if (!function_exists($_name)) { $_message = "modifier '$_name' is not implemented"; } else { $_plugin_func = $_name; $_found = true; } } } else if ($_type == 'function') { /* * This is a catch-all situation. */ $_message = "unknown tag - '$_name'"; } } if ($_found) { $smarty->_plugins[$_type][$_name] = array($_plugin_func, $_tpl_file, $_tpl_line, true, true); } else { // output error $smarty->_trigger_fatal_error('[plugin] ' . $_message, $_tpl_file, $_tpl_line, __FILE__, __LINE__); } } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.load_plugins.php
PHP
asf20
4,429
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * read a cache file, determine if it needs to be * regenerated or not * * @param string $tpl_file * @param string $cache_id * @param string $compile_id * @param string $results * @return boolean */ // $tpl_file, $cache_id, $compile_id, &$results function smarty_core_read_cache_file(&$params, &$smarty) { static $content_cache = array(); if ($smarty->force_compile) { // force compile enabled, always regenerate return false; } if (isset($content_cache[$params['tpl_file'].','.$params['cache_id'].','.$params['compile_id']])) { list($params['results'], $smarty->_cache_info) = $content_cache[$params['tpl_file'].','.$params['cache_id'].','.$params['compile_id']]; return true; } if (!empty($smarty->cache_handler_func)) { // use cache_handler function call_user_func_array($smarty->cache_handler_func, array('read', &$smarty, &$params['results'], $params['tpl_file'], $params['cache_id'], $params['compile_id'], null)); } else { // use local cache file $_auto_id = $smarty->_get_auto_id($params['cache_id'], $params['compile_id']); $_cache_file = $smarty->_get_auto_filename($smarty->cache_dir, $params['tpl_file'], $_auto_id); $params['results'] = $smarty->_read_file($_cache_file); } if (empty($params['results'])) { // nothing to parse (error?), regenerate cache return false; } $_contents = $params['results']; $_info_start = strpos($_contents, "\n") + 1; $_info_len = (int)substr($_contents, 0, $_info_start - 1); $_cache_info = unserialize(substr($_contents, $_info_start, $_info_len)); $params['results'] = substr($_contents, $_info_start + $_info_len); if ($smarty->caching == 2 && isset ($_cache_info['expires'])){ // caching by expiration time if ($_cache_info['expires'] > -1 && (time() > $_cache_info['expires'])) { // cache expired, regenerate return false; } } else { // caching by lifetime if ($smarty->cache_lifetime > -1 && (time() - $_cache_info['timestamp'] > $smarty->cache_lifetime)) { // cache expired, regenerate return false; } } if ($smarty->compile_check) { $_params = array('get_source' => false, 'quiet'=>true); foreach (array_keys($_cache_info['template']) as $_template_dep) { $_params['resource_name'] = $_template_dep; if (!$smarty->_fetch_resource_info($_params) || $_cache_info['timestamp'] < $_params['resource_timestamp']) { // template file has changed, regenerate cache return false; } } if (isset($_cache_info['config'])) { $_params = array('resource_base_path' => $smarty->config_dir, 'get_source' => false, 'quiet'=>true); foreach (array_keys($_cache_info['config']) as $_config_dep) { $_params['resource_name'] = $_config_dep; if (!$smarty->_fetch_resource_info($_params) || $_cache_info['timestamp'] < $_params['resource_timestamp']) { // config file has changed, regenerate cache return false; } } } } $content_cache[$params['tpl_file'].','.$params['cache_id'].','.$params['compile_id']] = array($params['results'], $_cache_info); $smarty->_cache_info = $_cache_info; return true; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.read_cache_file.php
PHP
asf20
3,604
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * determines if a resource is secure or not. * * @param string $resource_type * @param string $resource_name * @return boolean */ // $resource_type, $resource_name function smarty_core_is_secure($params, &$smarty) { if (!$smarty->security || $smarty->security_settings['INCLUDE_ANY']) { return true; } if ($params['resource_type'] == 'file') { $_rp = realpath($params['resource_name']); if (isset($params['resource_base_path'])) { foreach ((array)$params['resource_base_path'] as $curr_dir) { if ( ($_cd = realpath($curr_dir)) !== false && strncmp($_rp, $_cd, strlen($_cd)) == 0 && substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR ) { return true; } } } if (!empty($smarty->secure_dir)) { foreach ((array)$smarty->secure_dir as $curr_dir) { if ( ($_cd = realpath($curr_dir)) !== false) { if($_cd == $_rp) { return true; } elseif (strncmp($_rp, $_cd, strlen($_cd)) == 0 && substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR) { return true; } } } } } else { // resource is not on local file system return call_user_func_array( $smarty->_plugins['resource'][$params['resource_type']][0][2], array($params['resource_name'], &$smarty)); } return false; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.is_secure.php
PHP
asf20
1,694
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Handle insert tags * * @param array $args * @return string */ function smarty_core_run_insert_handler($params, &$smarty) { require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); if ($smarty->debugging) { $_params = array(); $_debug_start_time = smarty_core_get_microtime($_params, $smarty); } if ($smarty->caching) { $_arg_string = serialize($params['args']); $_name = $params['args']['name']; if (!isset($smarty->_cache_info['insert_tags'][$_name])) { $smarty->_cache_info['insert_tags'][$_name] = array('insert', $_name, $smarty->_plugins['insert'][$_name][1], $smarty->_plugins['insert'][$_name][2], !empty($params['args']['script']) ? true : false); } return $smarty->_smarty_md5."{insert_cache $_arg_string}".$smarty->_smarty_md5; } else { if (isset($params['args']['script'])) { $_params = array('resource_name' => $smarty->_dequote($params['args']['script'])); require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php'); if(!smarty_core_get_php_resource($_params, $smarty)) { return false; } if ($_params['resource_type'] == 'file') { $smarty->_include($_params['php_resource'], true); } else { $smarty->_eval($_params['php_resource']); } unset($params['args']['script']); } $_funcname = $smarty->_plugins['insert'][$params['args']['name']][0]; $_content = $_funcname($params['args'], $smarty); if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $smarty->_smarty_debug_info[] = array('type' => 'insert', 'filename' => 'insert_'.$params['args']['name'], 'depth' => $smarty->_inclusion_depth, 'exec_time' => smarty_core_get_microtime($_params, $smarty) - $_debug_start_time); } if (!empty($params['args']["assign"])) { $smarty->assign($params['args']["assign"], $_content); } else { return $_content; } } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.run_insert_handler.php
PHP
asf20
2,656
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * write the compiled resource * * @param string $compile_path * @param string $compiled_content * @return true */ function smarty_core_write_compiled_resource($params, &$smarty) { if(!@is_writable($smarty->compile_dir)) { // compile_dir not writable, see if it exists if(!@is_dir($smarty->compile_dir)) { $smarty->trigger_error('the $compile_dir \'' . $smarty->compile_dir . '\' does not exist, or is not a directory.', E_USER_ERROR); return false; } $smarty->trigger_error('unable to write to $compile_dir \'' . realpath($smarty->compile_dir) . '\'. Be sure $compile_dir is writable by the web server user.', E_USER_ERROR); return false; } $_params = array('filename' => $params['compile_path'], 'contents' => $params['compiled_content'], 'create_dirs' => true); require_once(SMARTY_CORE_DIR . 'core.write_file.php'); smarty_core_write_file($_params, $smarty); return true; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/internals/core.write_compiled_resource.php
PHP
asf20
1,081
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {config_load} function plugin * * Type: function<br> * Name: config_load<br> * Purpose: load config file vars * @link http://smarty.php.net/manual/en/language.function.config.load.php {config_load} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @author messju mohr <messju at lammfellpuschen dot de> (added use of resources) * @param array Format: * <pre> * array('file' => required config file name, * 'section' => optional config file section to load * 'scope' => local/parent/global * 'global' => overrides scope, setting to parent if true) * </pre> * @param Smarty */ function smarty_function_config_load($params, &$smarty) { if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $_debug_start_time = smarty_core_get_microtime($_params, $smarty); } $_file = isset($params['file']) ? $smarty->_dequote($params['file']) : null; $_section = isset($params['section']) ? $smarty->_dequote($params['section']) : null; $_scope = isset($params['scope']) ? $smarty->_dequote($params['scope']) : 'global'; $_global = isset($params['global']) ? $smarty->_dequote($params['global']) : false; if (!isset($_file) || strlen($_file) == 0) { $smarty->trigger_error("missing 'file' attribute in config_load tag", E_USER_ERROR, __FILE__, __LINE__); } if (isset($_scope)) { if ($_scope != 'local' && $_scope != 'parent' && $_scope != 'global') { $smarty->trigger_error("invalid 'scope' attribute value", E_USER_ERROR, __FILE__, __LINE__); } } else { if ($_global) { $_scope = 'parent'; } else { $_scope = 'local'; } } $_params = array('resource_name' => $_file, 'resource_base_path' => $smarty->config_dir, 'get_source' => false); $smarty->_parse_resource_name($_params); $_file_path = $_params['resource_type'] . ':' . $_params['resource_name']; if (isset($_section)) $_compile_file = $smarty->_get_compile_path($_file_path.'|'.$_section); else $_compile_file = $smarty->_get_compile_path($_file_path); if($smarty->force_compile || !file_exists($_compile_file)) { $_compile = true; } elseif ($smarty->compile_check) { $_params = array('resource_name' => $_file, 'resource_base_path' => $smarty->config_dir, 'get_source' => false); $_compile = $smarty->_fetch_resource_info($_params) && $_params['resource_timestamp'] > filemtime($_compile_file); } else { $_compile = false; } if($_compile) { // compile config file if(!is_object($smarty->_conf_obj)) { require_once SMARTY_DIR . $smarty->config_class . '.class.php'; $smarty->_conf_obj = new $smarty->config_class(); $smarty->_conf_obj->overwrite = $smarty->config_overwrite; $smarty->_conf_obj->booleanize = $smarty->config_booleanize; $smarty->_conf_obj->read_hidden = $smarty->config_read_hidden; $smarty->_conf_obj->fix_newlines = $smarty->config_fix_newlines; } $_params = array('resource_name' => $_file, 'resource_base_path' => $smarty->config_dir, $_params['get_source'] = true); if (!$smarty->_fetch_resource_info($_params)) { return; } $smarty->_conf_obj->set_file_contents($_file, $_params['source_content']); $_config_vars = array_merge($smarty->_conf_obj->get($_file), $smarty->_conf_obj->get($_file, $_section)); if(function_exists('var_export')) { $_output = '<?php $_config_vars = ' . var_export($_config_vars, true) . '; ?>'; } else { $_output = '<?php $_config_vars = unserialize(\'' . strtr(serialize($_config_vars),array('\''=>'\\\'', '\\'=>'\\\\')) . '\'); ?>'; } $_params = (array('compile_path' => $_compile_file, 'compiled_content' => $_output, 'resource_timestamp' => $_params['resource_timestamp'])); require_once(SMARTY_CORE_DIR . 'core.write_compiled_resource.php'); smarty_core_write_compiled_resource($_params, $smarty); } else { include($_compile_file); } if ($smarty->caching) { $smarty->_cache_info['config'][$_file] = true; } $smarty->_config[0]['vars'] = @array_merge($smarty->_config[0]['vars'], $_config_vars); $smarty->_config[0]['files'][$_file] = true; if ($_scope == 'parent') { $smarty->_config[1]['vars'] = @array_merge($smarty->_config[1]['vars'], $_config_vars); $smarty->_config[1]['files'][$_file] = true; } else if ($_scope == 'global') { for ($i = 1, $for_max = count($smarty->_config); $i < $for_max; $i++) { $smarty->_config[$i]['vars'] = @array_merge($smarty->_config[$i]['vars'], $_config_vars); $smarty->_config[$i]['files'][$_file] = true; } } if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $smarty->_smarty_debug_info[] = array('type' => 'config', 'filename' => $_file.' ['.$_section.'] '.$_scope, 'depth' => $smarty->_inclusion_depth, 'exec_time' => smarty_core_get_microtime($_params, $smarty) - $_debug_start_time); } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.config_load.php
PHP
asf20
6,158
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_table} function plugin * * Type: function<br> * Name: html_table<br> * Date: Feb 17, 2003<br> * Purpose: make an html table from an array of data<br> * Input:<br> * - loop = array to loop through * - cols = number of categorys, comma separated list of category names * or array of category names * - rows = number of rows * - table_attr = table attributes * - th_attr = table heading attributes (arrays are cycled) * - tr_attr = table row attributes (arrays are cycled) * - td_attr = table cell attributes (arrays are cycled) * - trailpad = value to pad trailing cells with * - caption = text for caption element * - vdir = vertical direction (default: "down", means top-to-bottom) * - hdir = horizontal direction (default: "right", means left-to-right) * - inner = inner loop (default "cols": print $loop line by line, * $loop will be printed category by category otherwise) * * * Examples: * <pre> * {table loop=$data} * {table loop=$data cols=4 tr_attr='"bgcolor=red"'} * {table loop=$data cols="first,second,third" tr_attr=$colors} * </pre> * @author Monte Ohrt <monte at ohrt dot com> * @author credit to Messju Mohr <messju at lammfellpuschen dot de> * @author credit to boots <boots dot smarty at yahoo dot com> * @version 1.1 * @link http://smarty.php.net/manual/en/language.function.html.table.php {html_table} * (Smarty online manual) * @param array * @param Smarty * @return string */ function smarty_function_html_table($params, &$smarty) { $table_attr = 'border="1"'; $tr_attr = ''; $th_attr = ''; $td_attr = ''; $cols = $cols_count = 3; $rows = 3; $trailpad = '&nbsp;'; $vdir = 'down'; $hdir = 'right'; $inner = 'cols'; $caption = ''; if (!isset($params['loop'])) { $smarty->trigger_error("html_table: missing 'loop' parameter"); return; } foreach ($params as $_key=>$_value) { switch ($_key) { case 'loop': $$_key = (array)$_value; break; case 'cols': if (is_array($_value) && !empty($_value)) { $cols = $_value; $cols_count = count($_value); } elseif (!is_numeric($_value) && is_string($_value) && !empty($_value)) { $cols = explode(',', $_value); $cols_count = count($cols); } elseif (!empty($_value)) { $cols_count = (int)$_value; } else { $cols_count = $cols; } break; case 'rows': $$_key = (int)$_value; break; case 'table_attr': case 'trailpad': case 'hdir': case 'vdir': case 'inner': case 'caption': $$_key = (string)$_value; break; case 'tr_attr': case 'td_attr': case 'th_attr': $$_key = $_value; break; } } $loop_count = count($loop); if (empty($params['rows'])) { /* no rows specified */ $rows = ceil($loop_count/$cols_count); } elseif (empty($params['cols'])) { if (!empty($params['rows'])) { /* no cols specified, but rows */ $cols_count = ceil($loop_count/$rows); } } $output = "<table $table_attr>\n"; if (!empty($caption)) { $output .= '<caption>' . $caption . "</caption>\n"; } if (is_array($cols)) { $cols = ($hdir == 'right') ? $cols : array_reverse($cols); $output .= "<thead><tr>\n"; for ($r=0; $r<$cols_count; $r++) { $output .= '<th' . smarty_function_html_table_cycle('th', $th_attr, $r) . '>'; $output .= $cols[$r]; $output .= "</th>\n"; } $output .= "</tr></thead>\n"; } $output .= "<tbody>\n"; for ($r=0; $r<$rows; $r++) { $output .= "<tr" . smarty_function_html_table_cycle('tr', $tr_attr, $r) . ">\n"; $rx = ($vdir == 'down') ? $r*$cols_count : ($rows-1-$r)*$cols_count; for ($c=0; $c<$cols_count; $c++) { $x = ($hdir == 'right') ? $rx+$c : $rx+$cols_count-1-$c; if ($inner!='cols') { /* shuffle x to loop over rows*/ $x = floor($x/$cols_count) + ($x%$cols_count)*$rows; } if ($x<$loop_count) { $output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">" . $loop[$x] . "</td>\n"; } else { $output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">$trailpad</td>\n"; } } $output .= "</tr>\n"; } $output .= "</tbody>\n"; $output .= "</table>\n"; return $output; } function smarty_function_html_table_cycle($name, $var, $no) { if(!is_array($var)) { $ret = $var; } else { $ret = $var[$no % count($var)]; } return ($ret) ? ' '.$ret : ''; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.html_table.php
PHP
asf20
5,530
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {assign} compiler function plugin * * Type: compiler function<br> * Name: assign<br> * Purpose: assign a value to a template variable * @link http://smarty.php.net/manual/en/language.custom.functions.php#LANGUAGE.FUNCTION.ASSIGN {assign} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> (initial author) * @author messju mohr <messju at lammfellpuschen dot de> (conversion to compiler function) * @param string containing var-attribute and value-attribute * @param Smarty_Compiler */ function smarty_compiler_assign($tag_attrs, &$compiler) { $_params = $compiler->_parse_attrs($tag_attrs); if (!isset($_params['var'])) { $compiler->_syntax_error("assign: missing 'var' parameter", E_USER_WARNING); return; } if (!isset($_params['value'])) { $compiler->_syntax_error("assign: missing 'value' parameter", E_USER_WARNING); return; } return "\$this->assign({$_params['var']}, {$_params['value']});"; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/compiler.assign.php
PHP
asf20
1,123
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty count_words modifier plugin * * Type: modifier<br> * Name: count_words<br> * Purpose: count the number of words in a text * @link http://smarty.php.net/manual/en/language.modifier.count.words.php * count_words (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return integer */ function smarty_modifier_count_words($string) { // split text by ' ',\r,\n,\f,\t $split_array = preg_split('/\s+/',$string); // count matches that contain alphanumerics $word_count = preg_grep('/[a-zA-Z0-9\\x80-\\xff]/', $split_array); return count($word_count); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.count_words.php
PHP
asf20
751
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty count_sentences modifier plugin * * Type: modifier<br> * Name: count_sentences * Purpose: count the number of sentences in a text * @link http://smarty.php.net/manual/en/language.modifier.count.paragraphs.php * count_sentences (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return integer */ function smarty_modifier_count_sentences($string) { // find periods with a word before but not after. return preg_match_all('/[^\s]\.(?!\w)/', $string, $match); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.count_sentences.php
PHP
asf20
653
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_checkboxes} function plugin * * File: function.html_checkboxes.php<br> * Type: function<br> * Name: html_checkboxes<br> * Date: 24.Feb.2003<br> * Purpose: Prints out a list of checkbox input types<br> * Input:<br> * - name (optional) - string default "checkbox" * - values (required) - array * - options (optional) - associative array * - checked (optional) - array default not set * - separator (optional) - ie <br> or &nbsp; * - output (optional) - the output next to each checkbox * - assign (optional) - assign the output as an array to this variable * Examples: * <pre> * {html_checkboxes values=$ids output=$names} * {html_checkboxes values=$ids name='box' separator='<br>' output=$names} * {html_checkboxes values=$ids checked=$checked separator='<br>' output=$names} * </pre> * @link http://smarty.php.net/manual/en/language.function.html.checkboxes.php {html_checkboxes} * (Smarty online manual) * @author Christopher Kvarme <christopher.kvarme@flashjab.com> * @author credits to Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param array * @param Smarty * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_checkboxes($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); $name = 'checkbox'; $values = null; $options = null; $selected = null; $separator = ''; $labels = true; $output = null; $extra = ''; foreach($params as $_key => $_val) { switch($_key) { case 'name': case 'separator': $$_key = $_val; break; case 'labels': $$_key = (bool)$_val; break; case 'options': $$_key = (array)$_val; break; case 'values': case 'output': $$_key = array_values((array)$_val); break; case 'checked': case 'selected': $selected = array_map('strval', array_values((array)$_val)); break; case 'checkboxes': $smarty->trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead', E_USER_WARNING); $options = (array)$_val; break; case 'assign': break; default: if(!is_array($_val)) { $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"'; } else { $smarty->trigger_error("html_checkboxes: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (!isset($options) && !isset($values)) return ''; /* raise error here? */ settype($selected, 'array'); $_html_result = array(); if (isset($options)) { foreach ($options as $_key=>$_val) $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels); } else { foreach ($values as $_i=>$_key) { $_val = isset($output[$_i]) ? $output[$_i] : ''; $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels); } } if(!empty($params['assign'])) { $smarty->assign($params['assign'], $_html_result); } else { return implode("\n",$_html_result); } } function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels) { $_output = ''; if ($labels) $_output .= '<label>'; $_output .= '<input type="checkbox" name="' . smarty_function_escape_special_chars($name) . '[]" value="' . smarty_function_escape_special_chars($value) . '"'; if (in_array((string)$value, $selected)) { $_output .= ' checked="checked"'; } $_output .= $extra . ' />' . $output; if ($labels) $_output .= '</label>'; $_output .= $separator; return $_output; } ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.html_checkboxes.php
PHP
asf20
4,381
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty wordwrap modifier plugin * * Type: modifier<br> * Name: wordwrap<br> * Purpose: wrap a string of text at a given length * @link http://smarty.php.net/manual/en/language.modifier.wordwrap.php * wordwrap (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param integer * @param string * @param boolean * @return string */ function smarty_modifier_wordwrap($string,$length=80,$break="\n",$cut=false) { return wordwrap($string,$length,$break,$cut); } ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.wordwrap.php
PHP
asf20
613
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {cycle} function plugin * * Type: function<br> * Name: cycle<br> * Date: May 3, 2002<br> * Purpose: cycle through given values<br> * Input: * - name = name of cycle (optional) * - values = comma separated list of values to cycle, * or an array of values to cycle * (this can be left out for subsequent calls) * - reset = boolean - resets given var to true * - print = boolean - print var or not. default is true * - advance = boolean - whether or not to advance the cycle * - delimiter = the value delimiter, default is "," * - assign = boolean, assigns to template var instead of * printed. * * Examples:<br> * <pre> * {cycle values="#eeeeee,#d0d0d0d"} * {cycle name=row values="one,two,three" reset=true} * {cycle name=row} * </pre> * @link http://smarty.php.net/manual/en/language.function.cycle.php {cycle} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @author credit to Mark Priatel <mpriatel@rogers.com> * @author credit to Gerard <gerard@interfold.com> * @author credit to Jason Sweat <jsweat_php@yahoo.com> * @version 1.3 * @param array * @param Smarty * @return string|null */ function smarty_function_cycle($params, &$smarty) { static $cycle_vars; $name = (empty($params['name'])) ? 'default' : $params['name']; $print = (isset($params['print'])) ? (bool)$params['print'] : true; $advance = (isset($params['advance'])) ? (bool)$params['advance'] : true; $reset = (isset($params['reset'])) ? (bool)$params['reset'] : false; if (!in_array('values', array_keys($params))) { if(!isset($cycle_vars[$name]['values'])) { $smarty->trigger_error("cycle: missing 'values' parameter"); return; } } else { if(isset($cycle_vars[$name]['values']) && $cycle_vars[$name]['values'] != $params['values'] ) { $cycle_vars[$name]['index'] = 0; } $cycle_vars[$name]['values'] = $params['values']; } $cycle_vars[$name]['delimiter'] = (isset($params['delimiter'])) ? $params['delimiter'] : ','; if(is_array($cycle_vars[$name]['values'])) { $cycle_array = $cycle_vars[$name]['values']; } else { $cycle_array = explode($cycle_vars[$name]['delimiter'],$cycle_vars[$name]['values']); } if(!isset($cycle_vars[$name]['index']) || $reset ) { $cycle_vars[$name]['index'] = 0; } if (isset($params['assign'])) { $print = false; $smarty->assign($params['assign'], $cycle_array[$cycle_vars[$name]['index']]); } if($print) { $retval = $cycle_array[$cycle_vars[$name]['index']]; } else { $retval = null; } if($advance) { if ( $cycle_vars[$name]['index'] >= count($cycle_array) -1 ) { $cycle_vars[$name]['index'] = 0; } else { $cycle_vars[$name]['index']++; } } return $retval; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.cycle.php
PHP
asf20
3,192
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty strip_tags modifier plugin * * Type: modifier<br> * Name: strip_tags<br> * Purpose: strip html tags from text * @link http://smarty.php.net/manual/en/language.modifier.strip.tags.php * strip_tags (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param boolean * @return string */ function smarty_modifier_strip_tags($string, $replace_with_space = true) { if ($replace_with_space) return preg_replace('!<[^>]*?>!', ' ', $string); else return strip_tags($string); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.strip_tags.php
PHP
asf20
676
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {debug} function plugin * * Type: function<br> * Name: debug<br> * Date: July 1, 2002<br> * Purpose: popup debug window * @link http://smarty.php.net/manual/en/language.function.debug.php {debug} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param array * @param Smarty * @return string output from {@link Smarty::_generate_debug_output()} */ function smarty_function_debug($params, &$smarty) { if (isset($params['output'])) { $smarty->assign('_smarty_debug_output', $params['output']); } require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php'); return smarty_core_display_debug_console(null, $smarty); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.debug.php
PHP
asf20
835
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty default modifier plugin * * Type: modifier<br> * Name: default<br> * Purpose: designate default value for empty variables * @link http://smarty.php.net/manual/en/language.modifier.default.php * default (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @return string */ function smarty_modifier_default($string, $default = '') { if (!isset($string) || $string === '') return $default; else return $string; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.default.php
PHP
asf20
635
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty spacify modifier plugin * * Type: modifier<br> * Name: spacify<br> * Purpose: add spaces between characters in a string * @link http://smarty.php.net/manual/en/language.modifier.spacify.php * spacify (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @return string */ function smarty_modifier_spacify($string, $spacify_char = ' ') { return implode($spacify_char, preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY)); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.spacify.php
PHP
asf20
644
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_radios} function plugin * * File: function.html_radios.php<br> * Type: function<br> * Name: html_radios<br> * Date: 24.Feb.2003<br> * Purpose: Prints out a list of radio input types<br> * Input:<br> * - name (optional) - string default "radio" * - values (required) - array * - options (optional) - associative array * - checked (optional) - array default not set * - separator (optional) - ie <br> or &nbsp; * - output (optional) - the output next to each radio button * - assign (optional) - assign the output as an array to this variable * Examples: * <pre> * {html_radios values=$ids output=$names} * {html_radios values=$ids name='box' separator='<br>' output=$names} * {html_radios values=$ids checked=$checked separator='<br>' output=$names} * </pre> * @link http://smarty.php.net/manual/en/language.function.html.radios.php {html_radios} * (Smarty online manual) * @author Christopher Kvarme <christopher.kvarme@flashjab.com> * @author credits to Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param array * @param Smarty * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_radios($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); $name = 'radio'; $values = null; $options = null; $selected = null; $separator = ''; $labels = true; $label_ids = false; $output = null; $extra = ''; foreach($params as $_key => $_val) { switch($_key) { case 'name': case 'separator': $$_key = (string)$_val; break; case 'checked': case 'selected': if(is_array($_val)) { $smarty->trigger_error('html_radios: the "' . $_key . '" attribute cannot be an array', E_USER_WARNING); } else { $selected = (string)$_val; } break; case 'labels': case 'label_ids': $$_key = (bool)$_val; break; case 'options': $$_key = (array)$_val; break; case 'values': case 'output': $$_key = array_values((array)$_val); break; case 'radios': $smarty->trigger_error('html_radios: the use of the "radios" attribute is deprecated, use "options" instead', E_USER_WARNING); $options = (array)$_val; break; case 'assign': break; default: if(!is_array($_val)) { $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"'; } else { $smarty->trigger_error("html_radios: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (!isset($options) && !isset($values)) return ''; /* raise error here? */ $_html_result = array(); if (isset($options)) { foreach ($options as $_key=>$_val) $_html_result[] = smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids); } else { foreach ($values as $_i=>$_key) { $_val = isset($output[$_i]) ? $output[$_i] : ''; $_html_result[] = smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids); } } if(!empty($params['assign'])) { $smarty->assign($params['assign'], $_html_result); } else { return implode("\n",$_html_result); } } function smarty_function_html_radios_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids) { $_output = ''; if ($labels) { if($label_ids) { $_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!', '_', $name . '_' . $value)); $_output .= '<label for="' . $_id . '">'; } else { $_output .= '<label>'; } } $_output .= '<input type="radio" name="' . smarty_function_escape_special_chars($name) . '" value="' . smarty_function_escape_special_chars($value) . '"'; if ($labels && $label_ids) $_output .= ' id="' . $_id . '"'; if ((string)$value==$selected) { $_output .= ' checked="checked"'; } $_output .= $extra . ' />' . $output; if ($labels) $_output .= '</label>'; $_output .= $separator; return $_output; } ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.html_radios.php
PHP
asf20
4,841
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {textformat}{/textformat} block plugin * * Type: block function<br> * Name: textformat<br> * Purpose: format text a certain way with preset styles * or custom wrap/indent settings<br> * @link http://smarty.php.net/manual/en/language.function.textformat.php {textformat} * (Smarty online manual) * @param array * <pre> * Params: style: string (email) * indent: integer (0) * wrap: integer (80) * wrap_char string ("\n") * indent_char: string (" ") * wrap_boundary: boolean (true) * </pre> * @author Monte Ohrt <monte at ohrt dot com> * @param string contents of the block * @param Smarty clever simulation of a method * @return string string $content re-formatted */ function smarty_block_textformat($params, $content, &$smarty) { if (is_null($content)) { return; } $style = null; $indent = 0; $indent_first = 0; $indent_char = ' '; $wrap = 80; $wrap_char = "\n"; $wrap_cut = false; $assign = null; foreach ($params as $_key => $_val) { switch ($_key) { case 'style': case 'indent_char': case 'wrap_char': case 'assign': $$_key = (string)$_val; break; case 'indent': case 'indent_first': case 'wrap': $$_key = (int)$_val; break; case 'wrap_cut': $$_key = (bool)$_val; break; default: $smarty->trigger_error("textformat: unknown attribute '$_key'"); } } if ($style == 'email') { $wrap = 72; } // split into paragraphs $_paragraphs = preg_split('![\r\n][\r\n]!',$content); $_output = ''; for($_x = 0, $_y = count($_paragraphs); $_x < $_y; $_x++) { if ($_paragraphs[$_x] == '') { continue; } // convert mult. spaces & special chars to single space $_paragraphs[$_x] = preg_replace(array('!\s+!','!(^\s+)|(\s+$)!'), array(' ',''), $_paragraphs[$_x]); // indent first line if($indent_first > 0) { $_paragraphs[$_x] = str_repeat($indent_char, $indent_first) . $_paragraphs[$_x]; } // wordwrap sentences $_paragraphs[$_x] = wordwrap($_paragraphs[$_x], $wrap - $indent, $wrap_char, $wrap_cut); // indent lines if($indent > 0) { $_paragraphs[$_x] = preg_replace('!^!m', str_repeat($indent_char, $indent), $_paragraphs[$_x]); } } $_output = implode($wrap_char . $wrap_char, $_paragraphs); return $assign ? $smarty->assign($assign, $_output) : $_output; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/block.textformat.php
PHP
asf20
2,843
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty capitalize modifier plugin * * Type: modifier<br> * Name: capitalize<br> * Purpose: capitalize words in the string * @link http://smarty.php.net/manual/en/language.modifiers.php#LANGUAGE.MODIFIER.CAPITALIZE * capitalize (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_modifier_capitalize($string, $uc_digits = false) { smarty_modifier_capitalize_ucfirst(null, $uc_digits); return preg_replace_callback('!\'?\b\w(\w|\')*\b!', 'smarty_modifier_capitalize_ucfirst', $string); } function smarty_modifier_capitalize_ucfirst($string, $uc_digits = null) { static $_uc_digits = false; if(isset($uc_digits)) { $_uc_digits = $uc_digits; return; } if(substr($string[0],0,1) != "'" && !preg_match("!\d!",$string[0]) || $_uc_digits) return ucfirst($string[0]); else return $string[0]; } ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.capitalize.php
PHP
asf20
1,037
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty debug_print_var modifier plugin * * Type: modifier<br> * Name: debug_print_var<br> * Purpose: formats variable contents for display in the console * @link http://smarty.php.net/manual/en/language.modifier.debug.print.var.php * debug_print_var (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array|object * @param integer * @param integer * @return string */ function smarty_modifier_debug_print_var($var, $depth = 0, $length = 40) { $_replace = array( "\n" => '<i>\n</i>', "\r" => '<i>\r</i>', "\t" => '<i>\t</i>' ); switch (gettype($var)) { case 'array' : $results = '<b>Array (' . count($var) . ')</b>'; foreach ($var as $curr_key => $curr_val) { $results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b>' . strtr($curr_key, $_replace) . '</b> =&gt; ' . smarty_modifier_debug_print_var($curr_val, ++$depth, $length); $depth--; } break; case 'object' : $object_vars = get_object_vars($var); $results = '<b>' . get_class($var) . ' Object (' . count($object_vars) . ')</b>'; foreach ($object_vars as $curr_key => $curr_val) { $results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b> -&gt;' . strtr($curr_key, $_replace) . '</b> = ' . smarty_modifier_debug_print_var($curr_val, ++$depth, $length); $depth--; } break; case 'boolean' : case 'NULL' : case 'resource' : if (true === $var) { $results = 'true'; } elseif (false === $var) { $results = 'false'; } elseif (null === $var) { $results = 'null'; } else { $results = htmlspecialchars((string) $var); } $results = '<i>' . $results . '</i>'; break; case 'integer' : case 'float' : $results = htmlspecialchars((string) $var); break; case 'string' : $results = strtr($var, $_replace); if (strlen($var) > $length ) { $results = substr($var, 0, $length - 3) . '...'; } $results = htmlspecialchars('"' . $results . '"'); break; case 'unknown type' : default : $results = strtr((string) $var, $_replace); if (strlen($results) > $length ) { $results = substr($results, 0, $length - 3) . '...'; } $results = htmlspecialchars($results); } return $results; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.debug_print_var.php
PHP
asf20
2,884
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty indent modifier plugin * * Type: modifier<br> * Name: indent<br> * Purpose: indent lines of text * @link http://smarty.php.net/manual/en/language.modifier.indent.php * indent (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param integer * @param string * @return string */ function smarty_modifier_indent($string,$chars=4,$char=" ") { return preg_replace('!^!m',str_repeat($char,$chars),$string); } ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.indent.php
PHP
asf20
567
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {eval} function plugin * * Type: function<br> * Name: eval<br> * Purpose: evaluate a template variable as a template<br> * @link http://smarty.php.net/manual/en/language.function.eval.php {eval} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty */ function smarty_function_eval($params, &$smarty) { if (!isset($params['var'])) { $smarty->trigger_error("eval: missing 'var' parameter"); return; } if($params['var'] == '') { return; } $smarty->_compile_source('evaluated template', $params['var'], $_var_compiled); ob_start(); $smarty->_eval('?>' . $_var_compiled); $_contents = ob_get_contents(); ob_end_clean(); if (!empty($params['assign'])) { $smarty->assign($params['assign'], $_contents); } else { return $_contents; } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.eval.php
PHP
asf20
1,014
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty strip modifier plugin * * Type: modifier<br> * Name: strip<br> * Purpose: Replace all repeated spaces, newlines, tabs * with a single space or supplied replacement string.<br> * Example: {$var|strip} {$var|strip:"&nbsp;"} * Date: September 25th, 2002 * @link http://smarty.php.net/manual/en/language.modifier.strip.php * strip (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param string * @param string * @return string */ function smarty_modifier_strip($text, $replace = ' ') { return preg_replace('!\s+!', $replace, $text); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.strip.php
PHP
asf20
742
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {fetch} plugin * * Type: function<br> * Name: fetch<br> * Purpose: fetch file, web or ftp data and display results * @link http://smarty.php.net/manual/en/language.function.fetch.php {fetch} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string|null if the assign parameter is passed, Smarty assigns the * result to a template variable */ function smarty_function_fetch($params, &$smarty) { if (empty($params['file'])) { $smarty->_trigger_fatal_error("[plugin] parameter 'file' cannot be empty"); return; } $content = ''; if ($smarty->security && !preg_match('!^(http|ftp)://!i', $params['file'])) { $_params = array('resource_type' => 'file', 'resource_name' => $params['file']); require_once(SMARTY_CORE_DIR . 'core.is_secure.php'); if(!smarty_core_is_secure($_params, $smarty)) { $smarty->_trigger_fatal_error('[plugin] (secure mode) fetch \'' . $params['file'] . '\' is not allowed'); return; } // fetch the file if($fp = @fopen($params['file'],'r')) { while(!feof($fp)) { $content .= fgets ($fp,4096); } fclose($fp); } else { $smarty->_trigger_fatal_error('[plugin] fetch cannot read file \'' . $params['file'] . '\''); return; } } else { // not a local file if(preg_match('!^http://!i',$params['file'])) { // http fetch if($uri_parts = parse_url($params['file'])) { // set defaults $host = $server_name = $uri_parts['host']; $timeout = 30; $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"; $agent = "Smarty Template Engine ".$smarty->_version; $referer = ""; $uri = !empty($uri_parts['path']) ? $uri_parts['path'] : '/'; $uri .= !empty($uri_parts['query']) ? '?' . $uri_parts['query'] : ''; $_is_proxy = false; if(empty($uri_parts['port'])) { $port = 80; } else { $port = $uri_parts['port']; } if(!empty($uri_parts['user'])) { $user = $uri_parts['user']; } if(!empty($uri_parts['pass'])) { $pass = $uri_parts['pass']; } // loop through parameters, setup headers foreach($params as $param_key => $param_value) { switch($param_key) { case "file": case "assign": case "assign_headers": break; case "user": if(!empty($param_value)) { $user = $param_value; } break; case "pass": if(!empty($param_value)) { $pass = $param_value; } break; case "accept": if(!empty($param_value)) { $accept = $param_value; } break; case "header": if(!empty($param_value)) { if(!preg_match('![\w\d-]+: .+!',$param_value)) { $smarty->_trigger_fatal_error("[plugin] invalid header format '".$param_value."'"); return; } else { $extra_headers[] = $param_value; } } break; case "proxy_host": if(!empty($param_value)) { $proxy_host = $param_value; } break; case "proxy_port": if(!preg_match('!\D!', $param_value)) { $proxy_port = (int) $param_value; } else { $smarty->_trigger_fatal_error("[plugin] invalid value for attribute '".$param_key."'"); return; } break; case "agent": if(!empty($param_value)) { $agent = $param_value; } break; case "referer": if(!empty($param_value)) { $referer = $param_value; } break; case "timeout": if(!preg_match('!\D!', $param_value)) { $timeout = (int) $param_value; } else { $smarty->_trigger_fatal_error("[plugin] invalid value for attribute '".$param_key."'"); return; } break; default: $smarty->_trigger_fatal_error("[plugin] unrecognized attribute '".$param_key."'"); return; } } if(!empty($proxy_host) && !empty($proxy_port)) { $_is_proxy = true; $fp = fsockopen($proxy_host,$proxy_port,$errno,$errstr,$timeout); } else { $fp = fsockopen($server_name,$port,$errno,$errstr,$timeout); } if(!$fp) { $smarty->_trigger_fatal_error("[plugin] unable to fetch: $errstr ($errno)"); return; } else { if($_is_proxy) { fputs($fp, 'GET ' . $params['file'] . " HTTP/1.0\r\n"); } else { fputs($fp, "GET $uri HTTP/1.0\r\n"); } if(!empty($host)) { fputs($fp, "Host: $host\r\n"); } if(!empty($accept)) { fputs($fp, "Accept: $accept\r\n"); } if(!empty($agent)) { fputs($fp, "User-Agent: $agent\r\n"); } if(!empty($referer)) { fputs($fp, "Referer: $referer\r\n"); } if(isset($extra_headers) && is_array($extra_headers)) { foreach($extra_headers as $curr_header) { fputs($fp, $curr_header."\r\n"); } } if(!empty($user) && !empty($pass)) { fputs($fp, "Authorization: BASIC ".base64_encode("$user:$pass")."\r\n"); } fputs($fp, "\r\n"); while(!feof($fp)) { $content .= fgets($fp,4096); } fclose($fp); $csplit = split("\r\n\r\n",$content,2); $content = $csplit[1]; if(!empty($params['assign_headers'])) { $smarty->assign($params['assign_headers'],split("\r\n",$csplit[0])); } } } else { $smarty->_trigger_fatal_error("[plugin] unable to parse Url, check syntax"); return; } } else { // ftp fetch if($fp = @fopen($params['file'],'r')) { while(!feof($fp)) { $content .= fgets ($fp,4096); } fclose($fp); } else { $smarty->_trigger_fatal_error('[plugin] fetch cannot read file \'' . $params['file'] .'\''); return; } } } if (!empty($params['assign'])) { $smarty->assign($params['assign'],$content); } else { return $content; } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.fetch.php
PHP
asf20
8,964
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty plugin * * Type: modifier<br> * Name: nl2br<br> * Date: Feb 26, 2003 * Purpose: convert \r\n, \r or \n to <<br>> * Input:<br> * - contents = contents to replace * - preceed_test = if true, includes preceeding break tags * in replacement * Example: {$text|nl2br} * @link http://smarty.php.net/manual/en/language.modifier.nl2br.php * nl2br (Smarty online manual) * @version 1.0 * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_modifier_nl2br($string) { return nl2br($string); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.nl2br.php
PHP
asf20
717
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty count_paragraphs modifier plugin * * Type: modifier<br> * Name: count_paragraphs<br> * Purpose: count the number of paragraphs in a text * @link http://smarty.php.net/manual/en/language.modifier.count.paragraphs.php * count_paragraphs (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return integer */ function smarty_modifier_count_paragraphs($string) { // count \r or \n characters return count(preg_split('/[\r\n]+/', $string)); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.count_paragraphs.php
PHP
asf20
630
<?php /** * Smarty shared plugin * @package Smarty * @subpackage plugins */ /** * Function: smarty_make_timestamp<br> * Purpose: used by other smarty functions to make a timestamp * from a string. * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_make_timestamp($string) { if(empty($string)) { // use "now": $time = time(); } elseif (preg_match('/^\d{14}$/', $string)) { // it is mysql timestamp format of YYYYMMDDHHMMSS? $time = mktime(substr($string, 8, 2),substr($string, 10, 2),substr($string, 12, 2), substr($string, 4, 2),substr($string, 6, 2),substr($string, 0, 4)); } elseif (is_numeric($string)) { // it is a numeric string, we handle it as timestamp $time = (int)$string; } else { // strtotime should handle it $time = strtotime($string); if ($time == -1 || $time === false) { // strtotime() was not able to parse $string, use "now": $time = time(); } } return $time; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/shared.make_timestamp.php
PHP
asf20
1,167
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_select_date} plugin * * Type: function<br> * Name: html_select_date<br> * Purpose: Prints the dropdowns for date selection. * * ChangeLog:<br> * - 1.0 initial release * - 1.1 added support for +/- N syntax for begin * and end year values. (Monte) * - 1.2 added support for yyyy-mm-dd syntax for * time value. (Jan Rosier) * - 1.3 added support for choosing format for * month values (Gary Loescher) * - 1.3.1 added support for choosing format for * day values (Marcus Bointon) * - 1.3.2 support negative timestamps, force year * dropdown to include given date unless explicitly set (Monte) * - 1.3.4 fix behaviour of 0000-00-00 00:00:00 dates to match that * of 0000-00-00 dates (cybot, boots) * @link http://smarty.php.net/manual/en/language.function.html.select.date.php {html_select_date} * (Smarty online manual) * @version 1.3.4 * @author Andrei Zmievski * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string */ function smarty_function_html_select_date($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); require_once $smarty->_get_plugin_filepath('shared','make_timestamp'); require_once $smarty->_get_plugin_filepath('function','html_options'); /* Default values. */ $prefix = "Date_"; $start_year = strftime("%Y"); $end_year = $start_year; $display_days = true; $display_months = true; $display_years = true; $month_format = "%B"; /* Write months as numbers by default GL */ $month_value_format = "%m"; $day_format = "%02d"; /* Write day values using this format MB */ $day_value_format = "%d"; $year_as_text = false; /* Display years in reverse order? Ie. 2000,1999,.... */ $reverse_years = false; /* Should the select boxes be part of an array when returned from PHP? e.g. setting it to "birthday", would create "birthday[Day]", "birthday[Month]" & "birthday[Year]". Can be combined with prefix */ $field_array = null; /* <select size>'s of the different <select> tags. If not set, uses default dropdown. */ $day_size = null; $month_size = null; $year_size = null; /* Unparsed attributes common to *ALL* the <select>/<input> tags. An example might be in the template: all_extra ='class ="foo"'. */ $all_extra = null; /* Separate attributes for the tags. */ $day_extra = null; $month_extra = null; $year_extra = null; /* Order in which to display the fields. "D" -> day, "M" -> month, "Y" -> year. */ $field_order = 'MDY'; /* String printed between the different fields. */ $field_separator = "\n"; $time = time(); $all_empty = null; $day_empty = null; $month_empty = null; $year_empty = null; $extra_attrs = ''; foreach ($params as $_key=>$_value) { switch ($_key) { case 'prefix': case 'time': case 'start_year': case 'end_year': case 'month_format': case 'day_format': case 'day_value_format': case 'field_array': case 'day_size': case 'month_size': case 'year_size': case 'all_extra': case 'day_extra': case 'month_extra': case 'year_extra': case 'field_order': case 'field_separator': case 'month_value_format': case 'month_empty': case 'day_empty': case 'year_empty': $$_key = (string)$_value; break; case 'all_empty': $$_key = (string)$_value; $day_empty = $month_empty = $year_empty = $all_empty; break; case 'display_days': case 'display_months': case 'display_years': case 'year_as_text': case 'reverse_years': $$_key = (bool)$_value; break; default: if(!is_array($_value)) { $extra_attrs .= ' '.$_key.'="'.smarty_function_escape_special_chars($_value).'"'; } else { $smarty->trigger_error("html_select_date: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (preg_match('!^-\d+$!', $time)) { // negative timestamp, use date() $time = date('Y-m-d', $time); } // If $time is not in format yyyy-mm-dd if (preg_match('/^(\d{0,4}-\d{0,2}-\d{0,2})/', $time, $found)) { $time = $found[1]; } else { // use smarty_make_timestamp to get an unix timestamp and // strftime to make yyyy-mm-dd $time = strftime('%Y-%m-%d', smarty_make_timestamp($time)); } // Now split this in pieces, which later can be used to set the select $time = explode("-", $time); // make syntax "+N" or "-N" work with start_year and end_year if (preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match)) { if ($match[1] == '+') { $end_year = strftime('%Y') + $match[2]; } else { $end_year = strftime('%Y') - $match[2]; } } if (preg_match('!^(\+|\-)\s*(\d+)$!', $start_year, $match)) { if ($match[1] == '+') { $start_year = strftime('%Y') + $match[2]; } else { $start_year = strftime('%Y') - $match[2]; } } if (strlen($time[0]) > 0) { if ($start_year > $time[0] && !isset($params['start_year'])) { // force start year to include given date if not explicitly set $start_year = $time[0]; } if($end_year < $time[0] && !isset($params['end_year'])) { // force end year to include given date if not explicitly set $end_year = $time[0]; } } $field_order = strtoupper($field_order); $html_result = $month_result = $day_result = $year_result = ""; $field_separator_count = -1; if ($display_months) { $field_separator_count++; $month_names = array(); $month_values = array(); if(isset($month_empty)) { $month_names[''] = $month_empty; $month_values[''] = ''; } for ($i = 1; $i <= 12; $i++) { $month_names[$i] = strftime($month_format, mktime(0, 0, 0, $i, 1, 2000)); $month_values[$i] = strftime($month_value_format, mktime(0, 0, 0, $i, 1, 2000)); } $month_result .= '<select name='; if (null !== $field_array){ $month_result .= '"' . $field_array . '[' . $prefix . 'Month]"'; } else { $month_result .= '"' . $prefix . 'Month"'; } if (null !== $month_size){ $month_result .= ' size="' . $month_size . '"'; } if (null !== $month_extra){ $month_result .= ' ' . $month_extra; } if (null !== $all_extra){ $month_result .= ' ' . $all_extra; } $month_result .= $extra_attrs . '>'."\n"; $month_result .= smarty_function_html_options(array('output' => $month_names, 'values' => $month_values, 'selected' => (int)$time[1] ? strftime($month_value_format, mktime(0, 0, 0, (int)$time[1], 1, 2000)) : '', 'print_result' => false), $smarty); $month_result .= '</select>'; } if ($display_days) { $field_separator_count++; $days = array(); if (isset($day_empty)) { $days[''] = $day_empty; $day_values[''] = ''; } for ($i = 1; $i <= 31; $i++) { $days[] = sprintf($day_format, $i); $day_values[] = sprintf($day_value_format, $i); } $day_result .= '<select name='; if (null !== $field_array){ $day_result .= '"' . $field_array . '[' . $prefix . 'Day]"'; } else { $day_result .= '"' . $prefix . 'Day"'; } if (null !== $day_size){ $day_result .= ' size="' . $day_size . '"'; } if (null !== $all_extra){ $day_result .= ' ' . $all_extra; } if (null !== $day_extra){ $day_result .= ' ' . $day_extra; } $day_result .= $extra_attrs . '>'."\n"; $day_result .= smarty_function_html_options(array('output' => $days, 'values' => $day_values, 'selected' => $time[2], 'print_result' => false), $smarty); $day_result .= '</select>'; } if ($display_years) { $field_separator_count++; if (null !== $field_array){ $year_name = $field_array . '[' . $prefix . 'Year]'; } else { $year_name = $prefix . 'Year'; } if ($year_as_text) { $year_result .= '<input type="text" name="' . $year_name . '" value="' . $time[0] . '" size="4" maxlength="4"'; if (null !== $all_extra){ $year_result .= ' ' . $all_extra; } if (null !== $year_extra){ $year_result .= ' ' . $year_extra; } $year_result .= ' />'; } else { $years = range((int)$start_year, (int)$end_year); if ($reverse_years) { rsort($years, SORT_NUMERIC); } else { sort($years, SORT_NUMERIC); } $yearvals = $years; if(isset($year_empty)) { array_unshift($years, $year_empty); array_unshift($yearvals, ''); } $year_result .= '<select name="' . $year_name . '"'; if (null !== $year_size){ $year_result .= ' size="' . $year_size . '"'; } if (null !== $all_extra){ $year_result .= ' ' . $all_extra; } if (null !== $year_extra){ $year_result .= ' ' . $year_extra; } $year_result .= $extra_attrs . '>'."\n"; $year_result .= smarty_function_html_options(array('output' => $years, 'values' => $yearvals, 'selected' => $time[0], 'print_result' => false), $smarty); $year_result .= '</select>'; } } // Loop thru the field_order field for ($i = 0; $i <= 2; $i++){ $c = substr($field_order, $i, 1); switch ($c){ case 'D': $html_result .= $day_result; break; case 'M': $html_result .= $month_result; break; case 'Y': $html_result .= $year_result; break; } // Add the field seperator if($i < $field_separator_count) { $html_result .= $field_separator; } } return $html_result; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.html_select_date.php
PHP
asf20
11,955
<?php /** * Smarty shared plugin * @package Smarty * @subpackage plugins */ /** * escape_special_chars common function * * Function: smarty_function_escape_special_chars<br> * Purpose: used by other smarty functions to escape * special chars except for already escaped ones * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_function_escape_special_chars($string) { if(!is_array($string)) { $string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string); $string = htmlspecialchars($string); $string = str_replace(array('%%%SMARTY_START%%%','%%%SMARTY_END%%%'), array('&',';'), $string); } return $string; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/shared.escape_special_chars.php
PHP
asf20
774
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {popup} function plugin * * Type: function<br> * Name: popup<br> * Purpose: make text pop up in windows via overlib * @link http://smarty.php.net/manual/en/language.function.popup.php {popup} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string */ function smarty_function_popup($params, &$smarty) { $append = ''; foreach ($params as $_key=>$_value) { switch ($_key) { case 'text': case 'trigger': case 'function': case 'inarray': $$_key = (string)$_value; if ($_key == 'function' || $_key == 'inarray') $append .= ',' . strtoupper($_key) . ",'$_value'"; break; case 'caption': case 'closetext': case 'status': $append .= ',' . strtoupper($_key) . ",'" . str_replace("'","\'",$_value) . "'"; break; case 'fgcolor': case 'bgcolor': case 'textcolor': case 'capcolor': case 'closecolor': case 'textfont': case 'captionfont': case 'closefont': case 'fgbackground': case 'bgbackground': case 'caparray': case 'capicon': case 'background': case 'frame': $append .= ',' . strtoupper($_key) . ",'$_value'"; break; case 'textsize': case 'captionsize': case 'closesize': case 'width': case 'height': case 'border': case 'offsetx': case 'offsety': case 'snapx': case 'snapy': case 'fixx': case 'fixy': case 'padx': case 'pady': case 'timeout': case 'delay': $append .= ',' . strtoupper($_key) . ",$_value"; break; case 'sticky': case 'left': case 'right': case 'center': case 'above': case 'below': case 'noclose': case 'autostatus': case 'autostatuscap': case 'fullhtml': case 'hauto': case 'vauto': case 'mouseoff': case 'followmouse': case 'closeclick': if ($_value) $append .= ',' . strtoupper($_key); break; default: $smarty->trigger_error("[popup] unknown parameter $_key", E_USER_WARNING); } } if (empty($text) && !isset($inarray) && empty($function)) { $smarty->trigger_error("overlib: attribute 'text' or 'inarray' or 'function' required"); return false; } if (empty($trigger)) { $trigger = "onmouseover"; } $retval = $trigger . '="return overlib(\''.preg_replace(array("!'!","![\r\n]!"),array("\'",'\r'),$text).'\''; $retval .= $append . ');"'; if ($trigger == 'onmouseover') $retval .= ' onmouseout="nd();"'; return $retval; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.popup.php
PHP
asf20
3,280
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_options} function plugin * * Type: function<br> * Name: html_options<br> * Input:<br> * - name (optional) - string default "select" * - values (required if no options supplied) - array * - options (required if no values supplied) - associative array * - selected (optional) - string default not set * - output (required if not options supplied) - array * Purpose: Prints the list of <option> tags generated from * the passed parameters * @link http://smarty.php.net/manual/en/language.function.html.options.php {html_image} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_options($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); $name = null; $values = null; $options = null; $selected = array(); $output = null; $extra = ''; foreach($params as $_key => $_val) { switch($_key) { case 'name': $$_key = (string)$_val; break; case 'options': $$_key = (array)$_val; break; case 'values': case 'output': $$_key = array_values((array)$_val); break; case 'selected': $$_key = array_map('strval', array_values((array)$_val)); break; default: if(!is_array($_val)) { $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"'; } else { $smarty->trigger_error("html_options: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (!isset($options) && !isset($values)) return ''; /* raise error here? */ $_html_result = ''; if (isset($options)) { foreach ($options as $_key=>$_val) $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected); } else { foreach ($values as $_i=>$_key) { $_val = isset($output[$_i]) ? $output[$_i] : ''; $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected); } } if(!empty($name)) { $_html_result = '<select name="' . $name . '"' . $extra . '>' . "\n" . $_html_result . '</select>' . "\n"; } return $_html_result; } function smarty_function_html_options_optoutput($key, $value, $selected) { if(!is_array($value)) { $_html_result = '<option label="' . smarty_function_escape_special_chars($value) . '" value="' . smarty_function_escape_special_chars($key) . '"'; if (in_array((string)$key, $selected)) $_html_result .= ' selected="selected"'; $_html_result .= '>' . smarty_function_escape_special_chars($value) . '</option>' . "\n"; } else { $_html_result = smarty_function_html_options_optgroup($key, $value, $selected); } return $_html_result; } function smarty_function_html_options_optgroup($key, $values, $selected) { $optgroup_html = '<optgroup label="' . smarty_function_escape_special_chars($key) . '">' . "\n"; foreach ($values as $key => $value) { $optgroup_html .= smarty_function_html_options_optoutput($key, $value, $selected); } $optgroup_html .= "</optgroup>\n"; return $optgroup_html; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.html_options.php
PHP
asf20
3,797
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {popup_init} function plugin * * Type: function<br> * Name: popup_init<br> * Purpose: initialize overlib * @link http://smarty.php.net/manual/en/language.function.popup.init.php {popup_init} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string */ function smarty_function_popup_init($params, &$smarty) { $zindex = 1000; if (!empty($params['zindex'])) { $zindex = $params['zindex']; } if (!empty($params['src'])) { return '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:'.$zindex.';"></div>' . "\n" . '<script type="text/javascript" language="JavaScript" src="'.$params['src'].'"></script>' . "\n"; } else { $smarty->trigger_error("popup_init: missing src parameter"); } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.popup_init.php
PHP
asf20
979
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty upper modifier plugin * * Type: modifier<br> * Name: upper<br> * Purpose: convert string to uppercase * @link http://smarty.php.net/manual/en/language.modifier.upper.php * upper (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_modifier_upper($string) { return strtoupper($string); } ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.upper.php
PHP
asf20
481
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_image} function plugin * * Type: function<br> * Name: html_image<br> * Date: Feb 24, 2003<br> * Purpose: format HTML tags for the image<br> * Input:<br> * - file = file (and path) of image (required) * - height = image height (optional, default actual height) * - width = image width (optional, default actual width) * - basedir = base directory for absolute paths, default * is environment variable DOCUMENT_ROOT * - path_prefix = prefix for path output (optional, default empty) * * Examples: {html_image file="/images/masthead.gif"} * Output: <img src="/images/masthead.gif" width=400 height=23> * @link http://smarty.php.net/manual/en/language.function.html.image.php {html_image} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @author credits to Duda <duda@big.hu> - wrote first image function * in repository, helped with lots of functionality * @version 1.0 * @param array * @param Smarty * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_image($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); $alt = ''; $file = ''; $height = ''; $width = ''; $extra = ''; $prefix = ''; $suffix = ''; $path_prefix = ''; $server_vars = ($smarty->request_use_auto_globals) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS']; $basedir = isset($server_vars['DOCUMENT_ROOT']) ? $server_vars['DOCUMENT_ROOT'] : ''; foreach($params as $_key => $_val) { switch($_key) { case 'file': case 'height': case 'width': case 'dpi': case 'path_prefix': case 'basedir': $$_key = $_val; break; case 'alt': if(!is_array($_val)) { $$_key = smarty_function_escape_special_chars($_val); } else { $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; case 'link': case 'href': $prefix = '<a href="' . $_val . '">'; $suffix = '</a>'; break; default: if(!is_array($_val)) { $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"'; } else { $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (empty($file)) { $smarty->trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE); return; } if (substr($file,0,1) == '/') { $_image_path = $basedir . $file; } else { $_image_path = $file; } if(!isset($params['width']) || !isset($params['height'])) { if(!$_image_data = @getimagesize($_image_path)) { if(!file_exists($_image_path)) { $smarty->trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE); return; } else if(!is_readable($_image_path)) { $smarty->trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE); return; } else { $smarty->trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE); return; } } if ($smarty->security && ($_params = array('resource_type' => 'file', 'resource_name' => $_image_path)) && (require_once(SMARTY_CORE_DIR . 'core.is_secure.php')) && (!smarty_core_is_secure($_params, $smarty)) ) { $smarty->trigger_error("html_image: (secure) '$_image_path' not in secure directory", E_USER_NOTICE); } if(!isset($params['width'])) { $width = $_image_data[0]; } if(!isset($params['height'])) { $height = $_image_data[1]; } } if(isset($params['dpi'])) { if(strstr($server_vars['HTTP_USER_AGENT'], 'Mac')) { $dpi_default = 72; } else { $dpi_default = 96; } $_resize = $dpi_default/$params['dpi']; $width = round($width * $_resize); $height = round($height * $_resize); } return $prefix . '<img src="'.$path_prefix.$file.'" alt="'.$alt.'" width="'.$width.'" height="'.$height.'"'.$extra.' />' . $suffix; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.html_image.php
PHP
asf20
4,783
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {counter} function plugin * * Type: function<br> * Name: counter<br> * Purpose: print out a counter value * @author Monte Ohrt <monte at ohrt dot com> * @link http://smarty.php.net/manual/en/language.function.counter.php {counter} * (Smarty online manual) * @param array parameters * @param Smarty * @return string|null */ function smarty_function_counter($params, &$smarty) { static $counters = array(); $name = (isset($params['name'])) ? $params['name'] : 'default'; if (!isset($counters[$name])) { $counters[$name] = array( 'start'=>1, 'skip'=>1, 'direction'=>'up', 'count'=>1 ); } $counter =& $counters[$name]; if (isset($params['start'])) { $counter['start'] = $counter['count'] = (int)$params['start']; } if (!empty($params['assign'])) { $counter['assign'] = $params['assign']; } if (isset($counter['assign'])) { $smarty->assign($counter['assign'], $counter['count']); } if (isset($params['print'])) { $print = (bool)$params['print']; } else { $print = empty($counter['assign']); } if ($print) { $retval = $counter['count']; } else { $retval = null; } if (isset($params['skip'])) { $counter['skip'] = $params['skip']; } if (isset($params['direction'])) { $counter['direction'] = $params['direction']; } if ($counter['direction'] == "down") $counter['count'] -= $counter['skip']; else $counter['count'] += $counter['skip']; return $retval; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/function.counter.php
PHP
asf20
1,772
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty count_characters modifier plugin * * Type: modifier<br> * Name: count_characteres<br> * Purpose: count the number of characters in a text * @link http://smarty.php.net/manual/en/language.modifier.count.characters.php * count_characters (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param boolean include whitespace in the character count * @return integer */ function smarty_modifier_count_characters($string, $include_spaces = false) { if ($include_spaces) return(strlen($string)); return preg_match_all("/[^\s]/",$string, $match); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.count_characters.php
PHP
asf20
743
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Include the {@link shared.make_timestamp.php} plugin */ require_once $smarty->_get_plugin_filepath('shared', 'make_timestamp'); /** * Smarty date_format modifier plugin * * Type: modifier<br> * Name: date_format<br> * Purpose: format datestamps via strftime<br> * Input:<br> * - string: input date string * - format: strftime format for output * - default_date: default date if $string is empty * @link http://smarty.php.net/manual/en/language.modifier.date.format.php * date_format (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @param string * @return string|void * @uses smarty_make_timestamp() */ function smarty_modifier_date_format($string, $format = '%b %e, %Y', $default_date = '') { if ($string != '') { $timestamp = smarty_make_timestamp($string); } elseif ($default_date != '') { $timestamp = smarty_make_timestamp($default_date); } else { return; } if (DIRECTORY_SEPARATOR == '\\') { $_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T'); $_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S'); if (strpos($format, '%e') !== false) { $_win_from[] = '%e'; $_win_to[] = sprintf('%\' 2d', date('j', $timestamp)); } if (strpos($format, '%l') !== false) { $_win_from[] = '%l'; $_win_to[] = sprintf('%\' 2d', date('h', $timestamp)); } $format = str_replace($_win_from, $_win_to, $format); } return strftime($format, $timestamp); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.date_format.php
PHP
asf20
1,840
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty replace modifier plugin * * Type: modifier<br> * Name: replace<br> * Purpose: simple search/replace * @link http://smarty.php.net/manual/en/language.modifier.replace.php * replace (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @param string * @return string */ function smarty_modifier_replace($string, $search, $replace) { return str_replace($search, $replace, $string); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.replace.php
PHP
asf20
585
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty string_format modifier plugin * * Type: modifier<br> * Name: string_format<br> * Purpose: format strings via sprintf * @link http://smarty.php.net/manual/en/language.modifier.string.format.php * string_format (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @return string */ function smarty_modifier_string_format($string, $format) { return sprintf($format, $string); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.string_format.php
PHP
asf20
579
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty cat modifier plugin * * Type: modifier<br> * Name: cat<br> * Date: Feb 24, 2003 * Purpose: catenate a value to a variable * Input: string to catenate * Example: {$var|cat:"foo"} * @link http://smarty.php.net/manual/en/language.modifier.cat.php cat * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param string * @param string * @return string */ function smarty_modifier_cat($string, $cat) { return $string . $cat; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/2.0/01mvc/lib/Smarty/plugins/modifier.cat.php
PHP
asf20
623