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
<div class="h-24 b-d-b-c-ccc g-d-w l-h-24"> <span class="p-l-8 f-w-b">{{if isset($privilege)}}Privilege edit{{else}}Add new privilege{{/if}}</span> </div> <div class="grid_8 p-t-20 p-l-20 "> <form id="apri_frm" name="apri_frm" action="{{"admincp/excution"|base_url}}" method="POST" onsubmit="return false;" target="integration_asynchronous" autocomplete="off" > <!-- title --> <div class="p-r p-b-12"> <p>Name</p> <div class="p-r"> <input type="text" class="w-320 b-g-c-w validate[required]" value="{{$privilege->apri_name|default:''}}" minlength="10" maxlength="120" id="pri_name" name="pri_name" /> <input type="hidden" value="{{$privilege->apri_id|default:''}}" id="pri_id" name="pri_id" /> </div> </div> <div class="clear"></div> <!-- alias --> <div class="p-r p-b-12"> <p><label class="d-p-b w-i" for="pri_key">Keyword</label></p> <div class="p-r"> <input type="text" class="w-i b-g-c-w validate[required,custom[alias]]" value="{{$privilege->apri_key|default:''}}" minlength="10" maxlength="120" id="pri_key" name="pri_key" /> </div> </div> <div class="clear"></div> <div class="p-r p-b-12 f-l"> <div class="f-l grid_4"> <!-- birth --> <div class="p-r-2"> <div class="p-r"> <p><label class="d-p-b w-i" for="pri_position">Position</label></p> <input type="text" data-putto="#gr-err-1" class="w-i b-g-c-w validate[min[0],max[99]]" value="{{$privilege->apri_position|default:0}}" minlength="7" min="0" max="99" maxlength="20" id="pri_position" name="pri_position" /> </div> </div> </div> <div class="f-l grid_4"> <!-- year --> <div class="p-l-2"> <div class="p-r"> <p><label class="d-p-b w-i" for="pri_status">Status{{$privilege->apri_status}}</label></p> <div class="p-r"> <select id="pri_status" name="pri_status" class="w-i"> <option {{if $privilege->apri_status|default:'false'=='false'}}selected='1'{{/if}} value="false">Private</option> <option {{if $privilege->apri_status|default:'false'=='true'}}selected='1'{{/if}} value="true">Public</option> </select> </div> </div> </div> </div> <div class="clear"></div> <p id="gr-err-1" class="erb"></p> </div> <div class="clear"></div> <!-- alias --> <div class="p-r p-b-12"> <p><label class="d-p-b w-i" for="pri_desc">Description</label></p> <div class="p-r"> <textarea class="w-i b-g-c-w input" id="pri_desc" name="pri_desc" >{{$privilege->apri_description|default:''}}</textarea> </div> </div> <div class="clear"></div> <div class="p-r"> <div id="step-3-back" onclick="reset_pri()" class="b-t-c g-d-w f-l m-r-8">new</div> <div id="step-3-next" onclick="update_pri()" class="b-t-c g-d-w f-r">Save</div> <div class="clear"></div> </div> </form> <div class="clear"></div> </div>
0x6a
trunk/application/views/backend/01_privilege/02_editor.tpl
Smarty
asf20
4,291
{{include file="../include/01_head.tpl"}} {{include file="../include/02_menu.tpl"}} <script type="text/javascript">var base_url = "{{""|base_url}}", edialog, ndialog;</script> <div class="g-d-w- lh28 p-l-12 b-d-b-c-ccc f-w-b f-z-11">Privileges</div> <div class="b-g-c-eee- b-d-b-c-ccc p-4"> <div class="p-r"> <div class="grid_10 p-a t-0 l-0 b-0 b-g-c-w- z-i-1 b-d-c-ccc"> <div class="h-24 b-d-b-c-ccc l-h-24 g-d-w-"> <span class="p-l-8 f-w-b">List Privileges</span> <span class="p-r-8 p-l-20 f-r add c-s-p a" onclick="privilege_detail('')">Add</span> </div> <div class="p-a t-24 l-0 r-0 b-0 o-v-f-a"> <table class="classic-table wi"> <tr class="g-d-w l-h-16"> <td class="w-20"></td> <td>Name</td> <td class="w-40">Position</td> <td class="w-40">#</td> </tr> {{foreach $privileges as $pri}} <tr class="l-h-16"> <td class="w-20"><input type="checkbox" {{if $pri->apri_status==='true'}}checked="1"{{/if}}/></td> <td>{{$pri->apri_name}}</td> <td class="w-40">{{$pri->apri_position}}</td> <td class="w-40"> <img class="s-w-h c-s-p" onclick="privilege_detail('{{$pri->apri_id}}')" src='{{base_url()}}libraries/images/16/icon_edit.png' alt=""/> </td> </tr> {{/foreach}}{{if not isset($pri)}}<tr><td colspan="3" class="t-a-c">No data to display.</td></tr>{{/if}} </table> </div> </div> <div class="b-g-c-eee- p-r r-0 prefix_10"> <div id="editor_box" class="m-l-6 b-d-c-ccc p-r" style="min-height: 500px"> <div class="p-a t-0 l-0 b-0 r-0 tranf-w-50 d-p-n" style="z-index: 1001"></div> <div class="p-a t-0 l-0 b-0 r-0 b-g-ldg b-g-c-w i-l-d d-p-n" style="z-index: 1002"></div> <div class="content-biz"></div> <div class="clear"></div> </div> </div> <div class="clear"></div> </div> </div> <script type="text/javascript"> function privilege_detail(id){ backendloading(); $("#editor_box .content-biz").load( "{{base_url()}}admincp/privilege/editor/" + id, function() { backendloaded(); $("#apri_frm").validationEngine(); } ); } function update_pri(){ if( $('#apri_frm').validationEngine('validate') === false)return false; new backend({ url : "{{"admincp/privilege/save"|base_url}}", data : { apri_id : $("#pri_id").val(), apri_name : $("#pri_name").val(), apri_key : $("#pri_key").val(), apri_position : $("#pri_position").val(), apri_status : $("#pri_status").val(), apri_description : $("#pri_desc").val() }, datatype : "json", callback : function(data){ if(data.result<0){ new bckdialog({type:'error'}).open(data.message); }else{ uiMessage(data.message); } } }).call(); return false; } </script> {{include file="../include/04_foot.tpl"}}
0x6a
trunk/application/views/backend/01_privilege/01_privilege.tpl
Smarty
asf20
3,777
{{include file="../00_include/01_head.tpl"}} <script type="text/javascript">var base_url = "{{""|base_url}}", edialog, ndialog;</script> <div class='l-h-28 g-d-w b-r-t-4 p-l-20 b-d-b-c-ddd p-r dotum'> <span>Home</span> <span class="arrow_space"></span> <span>Logs</span> </div> <div class="p-20 m-h-500"> {{if not isset($smarty.session.auth_db.errors)}}Log is empty.{{/if}} {{foreach $smarty.session.auth_db.errors as $e}} <p>{{$e}}</p> {{/foreach}} </div> {{include file="../00_include/02_foot.tpl"}}
0x6a
trunk/application/views/backend/06_dblog/01_dblog.tpl
Smarty
asf20
559
{{include file='../frontend/include/01_head.tpl'}} <div class="product-banner"> <div class="gcontain l-50-pc reprefix-12 "> <div class="title">Project - What we did?</div> </div> </div> <div class="main"> <div class="gcontain l-50-pc reprefix-12"> <div class="p-t-40"> <div class="grid_7"> <div class="nav_bar p-b-40"> <div class="title">PHÂN LOẠI</div> <ul> {{foreach $projects as $item}} <li {{if $cate_project->cate_alias==$item->cate_alias}}class="active"{{/if}}><a href="{{'du-an/'|cat:$item->cate_alias|escape:'html'|site_url}}">{{$item->cate_title|escape:'html'|truncate:28}}</a></li> {{/foreach}} {{if not isset($item)}}<li><a>Đang cập nhật</a></li>{{/if}} </ul> <!-- <div class="back m-t-32">BACK TO SERVICES</div>--> </div> </div> <div class="grid_17"> <div class="intro prefix_1"> <div class="title"> <h2>{{$cate_project->cate_title|default:'Đang cập nhật.'|escape:'html'}}</h2> </div> {{$left=false}} {{foreach $project_list as $item}} {{$left=not $left}} <div class="grid_8 p-t-40"> <div class="projects {{if $left}}p-r-20{{else}}p-l-20{{/if}}"> <a href="{{'du-an/'|cat:$cate_project->cate_alias|cat:'/'|cat:$item->news_alias|site_url}}"> <img width="300" height="172" src="{{base_url()}}data/{{$item->news_thumb|escape:'html'}}" alt=""/> <h4>{{$item->news_title|escape:'html'}}</h4> </a> </div> </div> {{/foreach}} {{if not isset($item)}}<p class="p-t-40">Đang cập nhật</p>{{/if}} </div> </div> </div> </div> </div> <div class="clear"></div> <div class="p-r"> <div class="gcontain l-50-pc reprefix-12 "> <div class="foot-line"></div> </div> </div> <div class="clear"></div> {{include file='../frontend/include/02_foot.tpl'}}
0x6a
trunk/application/views/frontend/05_project.tpl
Smarty
asf20
2,462
{{include file='../frontend/include/01_head.tpl'}} <div class="service-banner"> <div class="gcontain l-50-pc reprefix-12 "> <div class="title">Service - What can we do for you?</div> </div> </div> <div class="main"> <div class="gcontain l-50-pc reprefix-12"> <div class="p-t-40"> <div class="grid_7"> <div class="nav_bar p-b-40"> <div class="title">{{$cate_service->cate_title|default:'Danh mục'|escape:'html'}}</div> <ul> {{foreach $services as $item}} <li><a href="{{'dich-vu/'|cat:$cate_service->cate_alias|cat:'/'|cat:$item->news_alias|escape:'html'|site_url}}">{{$item->news_title|escape:'html'|truncate:28}}</a></li> {{/foreach}} {{if not isset($item)}}<li><a>Đang cập nhật</a></li>{{/if}} </ul> <a href="{{'dich-vu'|site_url}}" style="color:#fff" class="back m-t-32 d-p-b">BACK TO SERVICES</a> </div> </div> <div class="grid_17"> <div class="intro prefix_1"> <div class="title"> <h2>{{$news_detail->news_title|default:'Dữ liệu đang cập nhật.'|escape:'html'}}</h2> </div> <div class="t-a-j p-t-40 mceContentBody"> <h1>Đề mục cấp 1</h1><br/> <h2>Đề mục cấp 2</h2><br/> <h3>Đề mục cấp 3</h3><br/> <h4>Đề mục cấp 4</h4><br/> {{$news_detail->news_content|default:'Dữ liệu đang cập nhật.'}} </div> <div class="clear"></div> </div> </div> </div> </div> </div> <div class="clear"></div> <div class="p-r"> <div class="gcontain l-50-pc reprefix-12 "> <div class="foot-line"></div> </div> </div> <div class="clear"></div> {{include file='../frontend/include/02_foot.tpl'}}
0x6a
trunk/application/views/frontend/04_service_detail.tpl
Smarty
asf20
2,163
{{include file='../frontend/include/01_head.tpl'}} <div class="product-banner"> <div class="gcontain l-50-pc reprefix-12 "> <div class="title">About Us - Get to know us better?</div> </div> </div> <div class="main"> <div class="gcontain l-50-pc reprefix-12"> <div class="p-t-40"> <div class="grid_7"> <div class="intro p-b-40"> <div class="title"><h2>{{$cate_danhmuc->cate_title|default:'Danh mục'|escape:'html'}}</h2></div> <ul class="list"> {{foreach $danhmucs as $item}} <li><a href="{{$item->cate_link|escape:'html'|base_url}}">{{$item->cate_title|escape:'html'|truncate:28}}</a></li> {{/foreach}} </ul> <!-- <div class="back m-t-32">BACK TO SERVICES</div>--> </div> </div> <div class="grid_17"> <div class="intro prefix_1"> <div class="title"> <h2>{{$news_detail->news_title|default:'Dữ liệu đang cập nhật.'|escape:'html'}}</h2> </div> <div class="t-a-j p-t-40 mceContentBody"> <h1>Đề mục cấp 1</h1><br/> <h2>Đề mục cấp 2</h2><br/> <h3>Đề mục cấp 3</h3><br/> <h4>Đề mục cấp 4</h4><br/> {{$news_detail->news_content|default:'Dữ liệu đang cập nhật.'}} </div> <div class="t-a-j"><b>Tags :</b> {{$news_detail->news_tag}}</div> <div class="clear"></div> </div> </div> </div> </div> </div> <div class="clear"></div> <div class="p-r"> <div class="gcontain l-50-pc reprefix-12 "> <div class="foot-line"></div> </div> </div> <div class="clear"></div> {{include file='../frontend/include/02_foot.tpl'}}
0x6a
trunk/application/views/frontend/02_about.tpl
Smarty
asf20
2,114
{{include file='../frontend/include/01_head.tpl'}} <div id="slider" class="slider b-g-c-ccc p-r"> <div class="gcontain h-g-10 l-50-pc reprefix-12 cycleSlider"> {{foreach $sliders as $slider}} <img src='/data/{{$slider->cate_thumb}}' width="960" height="400" alt=""/> {{/foreach}} </div> <div id="cycleNav" class="nav t-a-c"></div> </div> <div id="banner" class="banner"></div> <div class="main"> <div class="gcontain l-50-pc reprefix-12"> <div class="services"> <a class="event"><div></div>Events & Marketing</a> <a class="event2"><div></div>Printing</a> <a class="event3"><div></div>Design & Branding</a> <a class="event4"><div></div>Production</a> </div> <div class="intro"> <div class="left grid_12"> <div class="p-r-20"> <div class="title"> <h2>{{$cate_left->cate_title|default:'Chúng tôi có'|escape:'html'}}</h2> </div> <ul class="list"> {{foreach $news_left as $item}} <li><a href="{{'gioi-thieu/'|cat:$item->news_alias|site_url}}">{{$item->news_title|escape:'html'|truncate:68}}</a></li> {{/foreach}} </ul> </div> </div> <div class="right grid_12"> <div class="p-l-20"> <div class="title"> <h2>{{$cate_right->cate_title|default:'Chúng tôi sẽ giúp bạn'|escape:'html'}}</h2> </div> <ul class="list"> {{foreach $news_right as $item}} <li><a href="{{'gioi-thieu/'|cat:$item->news_alias|site_url}}">{{$item->news_title|escape:'html'|truncate:68}}</a></li> {{/foreach}} </ul> </div> </div> <div class="clear"></div> <div class="projects p-t-32"> <div class="title"> <h2>{{$cate_project->cate_title|default:'Các dự án đã thực hiện'|escape:'html'}} <a href="" class="f-r">Xem thêm ››</a></h2> </div> <div class="list" style="height: 212px"> <div class="left"> <a href="/du-an/{{$projects[0]->cate_alias}}.html"> <img width="300" height="172" src='{{$projects[0]->cate_thumb}}' alt=""/> <h3>{{$projects[0]->cate_title|default:'Đang cập nhật'|escape:'html'}}</h3> </a> </div> <div class="center"> <a href="/du-an/{{$projects[1]->cate_alias}}.html"> <img width="300" height="172" src='{{$projects[1]->cate_thumb}}' alt=""/> <h3>{{$projects[1]->cate_title|default:'Đang cập nhật'|escape:'html'}}</h3> </a> </div> <div class="right"> <a href="/du-an/{{$projects[2]->cate_alias}}.html"> <img width="300" height="172" src='{{$projects[2]->cate_thumb}}' alt=""/> <h3>{{$projects[2]->cate_title|default:'Đang cập nhật'|escape:'html'}}</h3> </a> </div> </div> </div> <div class="clear"></div> <div class="p-t-32"> <div class="title"> <h2>{{$cate_customer->cate_title|default:'Khách hàng của chúng tôi'|escape:'html'}}</h2> </div> <div class="list p-t-20 p-b-20"> <div class="b-d-c-ddd p-t-16 p-b-16" style="background-color: #fff"> {{foreach $customers as $cus}} <div class="customer"><a href="{{$cus->cate_link}}" target="{{$cus->cate_target|default:'normal'}}"><img src="/data/{{$cus->cate_thumb}}" alt=""/></a></div> {{/foreach}} <div class="clear"></div> </div> </div> </div> <div class="clear"></div> </div> </div> </div> <div class="clear"></div> <div class="p-r"> <div class="gcontain l-50-pc reprefix-12 "> <div class="foot-line"></div> </div> </div> <div class="clear"></div> {{include file='../frontend/include/02_foot.tpl'}}
0x6a
trunk/application/views/frontend/01_home.tpl
Smarty
asf20
4,682
<div id="banner" class="footer"> <div class="gcontain l-50-pc reprefix-12 "> <span style="float: left;color: #fff;line-height: 44px;">Copyright @2013 StartVN. All Rights Reverved.</span> <span style="float: right;color: #fff;line-height: 44px;">Địa chỉ : 28 Vũ Tông Phan - Phường An Phú - Quận 2 - TP.HCM</span> </div> </div>
0x6a
trunk/application/views/frontend/include/02_foot.tpl
Smarty
asf20
367
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Start work</title> <meta http-equiv="content-type" content="text/javascript;charset=UTF-8" /> <link type="text/css" rel="stylesheet" href="{{base_url()}}libraries/frontend/css/grid.css"/> <link type="text/css" rel="stylesheet" href="{{base_url()}}libraries/css/bubble.css"/> <link type="text/css" rel="stylesheet" href="{{base_url()}}libraries/frontend/css/frontend.styles.css"/> <link type="text/css" rel="stylesheet" href="{{base_url()}}libraries/typography/typography.css"/> <script type="text/javascript" src="{{base_url()}}libraries/script/jquery-1.9.0.js"></script> <script type="text/javascript" src="{{base_url()}}libraries/ui/js/jquery-ui-1.9.2.custom.js"></script> <link type="text/css" rel="stylesheet" href="{{base_url()}}libraries/ui/themes/base/jquery.ui.all.css"/> <script type="text/javascript" src="{{base_url()}}libraries/cycle/jquery.cycle.all.js"></script> <script type="text/javascript" src="{{base_url()}}libraries/validation-engine/jquery.validationEngine-vi.js"></script> <script type="text/javascript" src="{{base_url()}}libraries/validation-engine/jquery.validationEngine.js"></script> <script type="text/javascript" src="{{base_url()}}libraries/backend/backend.jquery.1.1.9.js"></script> <script type="text/javascript" src="{{base_url()}}libraries/frontend/js/frontend.jquery.js"></script> <script src='{{base_url()}}libraries/galleria/galleria-1.2.9.min.js'></script> <!-- <link rel="stylesheet" href="/libraries/galleria/themes/classic/galleria.classic.css">--> <!-- <script src='/libraries/galleria/themes/classic/galleria.classic.min.js'></script>--> <link rel="stylesheet" href="{{base_url()}}libraries/galleria/themes/folio/galleria.folio.css"> <!-- <script src='/libraries/galleria/themes/folio/galleria.folio.min.js'></script>--> </head> <body style="background-color: #fafafa"> <iframe id="integration_asynchronous" name="integration_asynchronous" style="position:absolute;width: 0;height: 0;border: none;padding: 0;margin: 0;"></iframe> {{include file='../include/03_reg.tpl'}} {{include file='../include/04_login.tpl'}} <div class="head"> <div class="first"> <div class="h-36 p-b-4 gcontain l-50-pc reprefix-12"> <div id="hotline" class="hotline p-t-8 p-b-8 p-l-32 l-h-20 grid_x p-r-8"> Hotline : <strong>0909 199 199 - (08) 6 2872 931</strong> </div> <div id="auth" class="auth p-t-8 p-l-32 p-b-8 p-r-8 l-h-20 grid_x f-r"> {{if isset($smarty.session.frontend.customer)}} <a href="#">{{$smarty.session.frontend.customer->cust_name}}</a> <span>&nbsp;&nbsp;|&nbsp;&nbsp;</span> <a href="/excution/logout">Đăng xuất</a> {{else}} <a href="JavaScript:reg();">Đăng ký</a> <span>&nbsp;&nbsp;|&nbsp;&nbsp;</span> <a href="JavaScript:login();">Đăng nhập</a> {{/if}} </div> </div> </div> <div class="second gcontain h-g-4 l-50-pc reprefix-12"> <div id="logo" class="grid_8 h-g-4"> <a href="start_home.html"> <img src="{{base_url()}}libraries/frontend/images/logo.png" alt=""/> </a> </div> <div id="nav" class="nav"> <ul> <li><a class="active" href="{{base_url()}}">TRANG CHỦ</a></li> <li><a href="{{'gioi-thieu'|site_url}}">GIỚI THIỆU</a></li> <li><a href="{{'dich-vu'|site_url}}">DỊCH VỤ</a></li> <li><a href="{{'du-an'|site_url}}">DỰ ÁN</a></li> <li><a href="{{'lien-he'|site_url}}">LIÊN LẠC</a></li> </ul> </div> </div> </div>
0x6a
trunk/application/views/frontend/include/01_head.tpl
Smarty
asf20
4,266
<div class="jfk-bubble jfk-bubble-promo gray regfrm hidden z-i-100" style="right: 50%; margin-right: -480px; top: 35px; opacity: 1; padding: 16px; display: none;"> <div class="jfk-bubble-closebtn notice btn" onclick="reg()"></div> <div class="jfk-bubble-content-id"> <div class="promo-content w-320"> <form id="cust_frm" name="cust_frm" action="/excution" method="POST" onsubmit="cust_reg();" target="integration_asynchronous" > <!-- title --> <div class="p-r p-b-12"> <p>Họ và tên</p> <div class="p-r"> <input type="text" class="w-i b-g-c-w validate[required]" value="" minlength="10" maxlength="120" id="cust_name" name="cust_name" /> </div> </div> <div class="clear"></div> <div class="p-r p-b-12"> <p><label class="d-p-b w-i" for="cust_email">Email</label></p> <div class="p-r"> <input type="text" class="w-i b-g-c-w validate[required,custom[email]]" value="" minlength="10" maxlength="120" id="cust_email" name="cust_email" /> </div> </div> <div class="clear"></div> <div class="p-r p-b-12"> <p><label class="d-p-b w-i" for="cust_password">Mật khẩu</label></p> <div class="p-r"> <input type="password" class="w-i b-g-c-w validate[required]" value="" minlength="10" maxlength="120" id="cust_password" name="cust_password" /> </div> </div> <div class="clear"></div> <div class="p-r p-b-12"> <p><label class="d-p-b w-i" for="re_cust_password">Xác nhận</label></p> <div class="p-r"> <input type="password" class="w-i b-g-c-w validate[required,equals[cust_password]]" value="" minlength="10" maxlength="120" id="re_cust_password" name="re_cust_password" /> </div> </div> <div class="clear"></div> <div class="p-r"> <input class="p-0 m-0 f-l" checked='1' disabled='1' type="checkbox"/><label for=""><span class="l-h-24 f-l" >Đồng ý với các điều khoản sử dụng.</span></label> <button class="b-t-c g-d-w f-r">Đăng ký</button> <div class="clear"></div> </div> <div id="cust_frm_err" class="p-r erc"></div> </form> </div> </div> <div class="jfk-bubble-arrow-id jfk-bubble-arrow jfk-bubble-arrowup" style="right: 108px"> <div class="jfk-bubble-arrowimplbefore"></div> <div class="jfk-bubble-arrowimplafter"></div> </div> </div>
0x6a
trunk/application/views/frontend/include/03_reg.tpl
Smarty
asf20
3,835
<div class="jfk-bubble jfk-bubble-promo gray loginfrm hidden z-i-100" style="right: 50%; margin-right: -480px; top: 35px; opacity: 1; padding: 16px; display: none;"> <div class="jfk-bubble-closebtn notice btn" onclick="login()"></div> <div class="jfk-bubble-content-id"> <div class="promo-content w-320"> <form id="login_frm" name="login_frm" action="/excution" method="POST" onsubmit="cust_login();" target="integration_asynchronous" > <div class="p-r p-b-12"> <p><label class="d-p-b w-i" for="login_email">Email</label></p> <div class="p-r"> <input type="text" class="w-i b-g-c-w validate[required,custom[email]]" value="" minlength="10" maxlength="120" id="login_email" name="login_email" /> </div> </div> <div class="clear"></div> <div class="p-r p-b-12"> <p><label class="d-p-b w-i" for="login_password">Mật khẩu</label></p> <div class="p-r"> <input type="password" class="w-i b-g-c-w validate[required]" value="" minlength="10" maxlength="120" id="login_password" name="login_password" /> </div> </div> <div class="clear"></div> <div class="p-r"> <button class="b-t-c g-d-w f-r">Đăng nhập</button> <div class="clear"></div> </div> <div id="login_frm_err" class="p-r erc"></div> </form> </div> </div> <div class="jfk-bubble-arrow-id jfk-bubble-arrow jfk-bubble-arrowup" style="right: 40px"> <div class="jfk-bubble-arrowimplbefore"></div> <div class="jfk-bubble-arrowimplafter"></div> </div> </div>
0x6a
trunk/application/views/frontend/include/04_login.tpl
Smarty
asf20
2,371
{{include file='../frontend/include/01_head.tpl'}} <div class="product-banner"> <div class="gcontain l-50-pc reprefix-12 "> <div class="title">Contact Us - What we did?</div> </div> </div> <div class="main"> <div class="gcontain l-50-pc reprefix-12"> <div class="p-t-40"> <div class="grid_7"> <div class="intro p-b-40"> <div class="title"><h2>{{$cate_danhmuc->cate_title|default:'Danh mục'|escape:'html'}}</h2></div> <ul class="onium" style="list-style: none"> <li class="aa"><span class="l-h-16">181/19, Hồng Lạc, P.10, Q.Tân Bình, TP. HCM</span></li> <li class="ab">PRINTING</li> <li class="ac">DESIGN &amp; BRANDING</li> <li class="ad">PRODUCTION</li> </ul> <!-- <div class="back m-t-32">BACK TO SERVICES</div>--> </div> </div> <div class="grid_17"> <div class="intro prefix_1"> <div class="title"> <h2>Liên hệ</h2> </div> <div class="t-a-j p-b-40 p-t-0"> <form id="cont_frm" name="cont_frm" action="{{"excution"|base_url}}" method="POST" onsubmit="addcontact();return false;" target="integration_asynchronous" > <div class="grid_8"> <br>Họ và tên<br> <input type="text" value="" id="cont_name" name="cont_name" class="classic-input w-280 validate[required] "> </div> <div class="grid_8"> <div class="p-l-40"> <br>Email<br> <input type="text" value="" id="cont_mail" name="cont_mail" class="classic-input w-280 validate[required,custom[email]] "> </div> </div> <div class="clear"></div> <div class="grid_16"> <br>Tiêu đề<br> <input type="text" value="" id="cont_subject" name="cont_subject" class="classic-input w-640 validate[required] "> </div> <div class="clear"></div> <div class="grid_16"> <br>Nội dung<br> <div style="padding-right: 10px"> <textarea id="cont_message" name="cont_message" class="w-i m-0 p-4 r-s-v validate[required]"></textarea> </div> </div> <div class="clear"></div> <div class="p-t-12"> <button class="b-t-c g-d-w f-l m-r-8 ">Gửi</button> </div> <div class="clear"></div> <div id="cont_frm_err" class="p-r erc"></div> <div class="clear"></div> </form> <div class="clear"></div> </div> <div class="clear"></div> </div> </div> </div> </div> </div> <div class="clear"></div> <div class="p-r"> <div class="gcontain l-50-pc reprefix-12 "> <div class="foot-line"></div> </div> </div> <div class="clear"></div> {{include file='../frontend/include/02_foot.tpl'}} <script> $(document).ready(function(){ $("#cont_frm").validationEngine(); }); function addcontact(){ if( $('#cont_frm').validationEngine('validate') === false)return false; $('#cont_frm_err').html('Đang xử lý...'); new backend({ url : "{{"/excution/addcontact"|base_url}}", data : $('#cont_frm').serialize(), callback : function(data){ if(data.result<0){ $('#cont_frm_err').html(data.message); }else{ document.cont_frm.reset(); $('#cont_frm_err').html('Đã gửi.'); } console.log(data); } }).call(); return false; } </script>
0x6a
trunk/application/views/frontend/07_contact.tpl
Smarty
asf20
4,755
{{include file='../frontend/include/01_head.tpl'}} <div class="product-banner"> <div class="gcontain l-50-pc reprefix-12 "> <div class="title">Project - What we did?</div> </div> </div> <div class="main"> <div class="gcontain l-50-pc reprefix-12"> <div class="p-t-40"> <div class="grid_7"> <div class="nav_bar p-b-40"> <div class="title">PHÂN LOẠI</div> <ul> {{foreach $projects as $item}} <li><a href="{{'du-an/'|cat:$item->cate_alias|escape:'html'|site_url}}">{{$item->cate_title|escape:'html'|truncate:28}}</a></li> {{/foreach}} {{if not isset($item)}}<li><a>Đang cập nhật</a></li>{{/if}} </ul> <!-- <div class="back m-t-32">BACK TO SERVICES</div>--> </div> </div> <div class="grid_17"> <div class="intro prefix_1"> <div class="title"> <h2>{{$news_detail->news_title|default:'Dữ liệu đang cập nhật.'|escape:'html'}}</h2> </div> <div class="t-a-j p-t-40 mceContentBody"> <h1>Đề mục cấp 1</h1><br/> <h2>Đề mục cấp 2</h2><br/> <h3>Đề mục cấp 3</h3><br/> <h4>Đề mục cấp 4</h4><br/> {{$news_detail->news_content|default:'Dữ liệu đang cập nhật.'}} </div> <div class="clear"></div> </div> </div> </div> </div> </div> <div class="clear"></div> <div class="p-r"> <div class="gcontain l-50-pc reprefix-12 "> <div class="foot-line"></div> </div> </div> <div class="clear"></div> {{include file='../frontend/include/02_foot.tpl'}}
0x6a
trunk/application/views/frontend/06_project_detail.tpl
Smarty
asf20
2,050
{{include file='../frontend/include/01_head.tpl'}} <div class="service-banner"> <div class="gcontain l-50-pc reprefix-12 "> <div class="title">Service - What can we do for you?</div> </div> </div> <div class="main"> <div class="gcontain l-50-pc reprefix-12"> {{if isset($services[0])}}{{$item=$services[0]}} <div class="grid_12 p-t-40"> <div class="service p-r-20"> <a class="d-p-b" href="{{'dich-vu/'|cat:$item->cate_alias|site_url}}"> <img width="460" height="200" src="{{base_url()}}data/{{$item->cate_thumb|escape:'html'}}" alt=""/> <div class="title"> {{$item->cate_title|default:'Đang cập nhật'|escape:'html'}} <img class="p-a t-0 push_10" src="{{base_url()}}libraries/frontend/images/calendar_icon.png" alt=""/> </div> </a> </div> </div> {{/if}} {{if isset($services[1])}}{{$item=$services[1]}} <div class="grid_12 p-t-40"> <div class="service p-l-20"> <a class="d-p-b" href="{{'dich-vu/'|cat:$item->cate_alias|site_url}}"> <img width="460" height="200" src="{{base_url()}}data/{{$item->cate_thumb|escape:'html'}}" alt=""/> <div class="title"> {{$item->cate_title|default:'Đang cập nhật'|escape:'html'}} <img class="p-a t-0 push_10" src="{{base_url()}}libraries/frontend/images/print_icon.png" alt=""/> </div> </a> </div> </div> {{/if}} {{if isset($services[2])}}{{$item=$services[2]}} <div class="grid_12 p-t-40"> <div class="service p-r-20"> <a class="d-p-b" href="{{'dich-vu/'|cat:$item->cate_alias|site_url}}"> <img width="460" height="200" src="{{base_url()}}data/{{$item->cate_thumb|escape:'html'}}" alt=""/> <div class="title"> {{$item->cate_title|default:'Đang cập nhật'|escape:'html'}} <img class="p-a t-0 push_10" src="{{base_url()}}libraries/frontend/images/paint_icon.png" alt=""/> </div> </a> </div> </div> {{/if}} {{if isset($services[3])}}{{$item=$services[3]}} <div class="grid_12 p-t-40"> <div class="service p-l-20"> <a class="d-p-b" href="{{'dich-vu/'|cat:$item->cate_alias|site_url}}"> <img width="460" height="200" src="{{base_url()}}data/{{$item->cate_thumb|escape:'html'}}" alt=""/> <div class="title"> {{$item->cate_title|default:'Đang cập nhật'|escape:'html'}} <img class="p-a t-0 push_10" src="{{base_url()}}libraries/frontend/images/camera_icon.png" alt=""/> </div> </a> </div> </div> {{/if}} </div> </div> <div class="clear"></div> <div class="p-r"> <div class="gcontain l-50-pc reprefix-12 "> <div class="foot-line"></div> </div> </div> <div class="clear"></div> {{include file='../frontend/include/02_foot.tpl'}}
0x6a
trunk/application/views/frontend/03_service.tpl
Smarty
asf20
3,370
<div class="p-20 backendplugin"> <div class="p-r p-b-12"> <p>Album Name</p> <div class="p-r"> <input type="text" class="w-i b-0xdd h-24" id="albu_alias" name="albu_alias" /> </div> </div> <div class="clear"></div> <div id="album_images_BKP"> <div class="t-a-c fontend_album classic_album" style="text-align: center;"></div> </div> <div class="mceContentBody "> <div id="choosefilefromserverBKP" class="pluginbutton grid_1 h-g-1 b-r-10 t-a-c c-s-p m-r-20" style="border: 4px dotted #55ea55;line-height: 40px;font-size: 30px;font-family: arial;color:#55ea55" onclick="BrowseServerCallBack(addAlbumItemBKP)" >+</div> <div id="choosefilefromserverBKP" class="pluginbutton grid_1 h-g-1 b-r-10 t-a-c c-s-p" style="border: 4px dotted #00CBFF;line-height: 40px;font-size: 30px;font-family: arial;color:#00CBFF" onclick="mceInsertContentBKP(addAlbumItemBKP)" >&check;</div> </div> </div> <script> function addAlbumItemBKP(url){ if(url!=undefined && url!=""){ var src=base_url+ '0x4D/' +url, thumb=base_url+'0x4D/0x00/'+url; if(url.indexOf('0x00')==0) thumb=base_url+'0x4D/'+url; $('#album_images_BKP .fontend_album').append('\ <a href="'+src+'">\ <img class="h-g-2 p-2 b-d-c-ccc m-r-4 m-b-4" data-big="' + src + '" data-description="My description" src="' + thumb + '"/>\ </a>\ '); } } function mceInsertContentBKP(){ var albumcontent='<p>&nbsp;</p>'+$('#album_images_BKP').html()+'<p>&nbsp;</p>'; tinyMCE.activeEditor.execCommand('mceInsertContent', false,albumcontent ); $('#frm_backend_album').dialog('close'); } </script>
0x6a
trunk/application/views/plugin/01_choosealbum.tpl
Smarty
asf20
1,898
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
0x6a
trunk/application/views/index.html
HTML
asf20
121
<?php /* * This is a PHP library that handles calling reCAPTCHA. * - Documentation and latest version * http://recaptcha.net/plugins/php/ * - Get a reCAPTCHA API Key * https://www.google.com/recaptcha/admin/create * - Discussion group * http://groups.google.com/group/recaptcha * * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net * AUTHORS: * Mike Crawford * Ben Maurer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * The reCAPTCHA server URL's */ define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api"); define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api"); define("RECAPTCHA_VERIFY_SERVER", "www.google.com"); /** * Encodes the given data into a query string format * @param $data - array of string elements to be encoded * @return string - encoded request */ function _recaptcha_qsencode ($data) { $req = ""; foreach ( $data as $key => $value ) $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; // Cut the last '&' $req=substr($req,0,strlen($req)-1); return $req; } /** * Submits an HTTP POST to a reCAPTCHA server * @param string $host * @param string $path * @param array $data * @param int port * @return array response */ function _recaptcha_http_post($host, $path, $data, $port = 80) { $req = _recaptcha_qsencode ($data); $http_request = "POST $path HTTP/1.0\r\n"; $http_request .= "Host: $host\r\n"; $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $http_request .= "Content-Length: " . strlen($req) . "\r\n"; $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; $http_request .= "\r\n"; $http_request .= $req; $response = ''; if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { die ('Could not open socket'); } fwrite($fs, $http_request); while ( !feof($fs) ) $response .= fgets($fs, 1160); // One TCP-IP packet fclose($fs); $response = explode("\r\n\r\n", $response, 2); return $response; } /** * Gets the challenge HTML (javascript and non-javascript version). * This is called from the browser, and the resulting reCAPTCHA HTML widget * is embedded within the HTML form it was called from. * @param string $pubkey A public key for reCAPTCHA * @param string $error The error given by reCAPTCHA (optional, default is null) * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false) * @return string - The HTML to be embedded in the user's form. */ function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) { if ($pubkey == null || $pubkey == '') { die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ($use_ssl) { $server = RECAPTCHA_API_SECURE_SERVER; } else { $server = RECAPTCHA_API_SERVER; } $errorpart = ""; if ($error) { $errorpart = "&amp;error=" . $error; } return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script> <noscript> <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/> </noscript>'; } /** * A ReCaptchaResponse is returned from recaptcha_check_answer() */ class ReCaptchaResponse { var $is_valid; var $error; } /** * Calls an HTTP POST function to verify if the user's guess was correct * @param string $privkey * @param string $remoteip * @param string $challenge * @param string $response * @param array $extra_params an array of extra variables to post to the server * @return ReCaptchaResponse */ function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()) { if ($privkey == null || $privkey == '') { die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ($remoteip == null || $remoteip == '') { die ("For security reasons, you must pass the remote ip to reCAPTCHA"); } //discard spam submissions if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { $recaptcha_response = new ReCaptchaResponse(); $recaptcha_response->is_valid = false; $recaptcha_response->error = 'incorrect-captcha-sol'; return $recaptcha_response; } $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify", array ( 'privatekey' => $privkey, 'remoteip' => $remoteip, 'challenge' => $challenge, 'response' => $response ) + $extra_params ); $answers = explode ("\n", $response [1]); $recaptcha_response = new ReCaptchaResponse(); if (trim ($answers [0]) == 'true') { $recaptcha_response->is_valid = true; } else { $recaptcha_response->is_valid = false; $recaptcha_response->error = $answers [1]; } return $recaptcha_response; } /** * gets a URL where the user can sign up for reCAPTCHA. If your application * has a configuration page where you enter a key, you should provide a link * using this function. * @param string $domain The domain where the page is hosted * @param string $appname The name of your application */ function recaptcha_get_signup_url ($domain = null, $appname = null) { return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname)); } function _recaptcha_aes_pad($val) { $block_size = 16; $numpad = $block_size - (strlen ($val) % $block_size); return str_pad($val, strlen ($val) + $numpad, chr($numpad)); } /* Mailhide related code */ function _recaptcha_aes_encrypt($val,$ky) { if (! function_exists ("mcrypt_encrypt")) { die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); } $mode=MCRYPT_MODE_CBC; $enc=MCRYPT_RIJNDAEL_128; $val=_recaptcha_aes_pad($val); return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); } function _recaptcha_mailhide_urlbase64 ($x) { return strtr(base64_encode ($x), '+/', '-_'); } /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ function recaptcha_mailhide_url($pubkey, $privkey, $email) { if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>"); } $ky = pack('H*', $privkey); $cryptmail = _recaptcha_aes_encrypt ($email, $ky); return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail); } /** * gets the parts of the email to expose to the user. * eg, given johndoe@example,com return ["john", "example.com"]. * the email is then displayed as john...@example.com */ function _recaptcha_mailhide_email_parts ($email) { $arr = preg_split("/@/", $email ); if (strlen ($arr[0]) <= 4) { $arr[0] = substr ($arr[0], 0, 1); } else if (strlen ($arr[0]) <= 6) { $arr[0] = substr ($arr[0], 0, 3); } else { $arr[0] = substr ($arr[0], 0, 4); } return $arr; } /** * Gets html to display an email address given a public an private key. * to get a key, go to: * * http://www.google.com/recaptcha/mailhide/apikey */ function recaptcha_mailhide_html($pubkey, $privkey, $email) { $emailparts = _recaptcha_mailhide_email_parts ($email); $url = recaptcha_mailhide_url ($pubkey, $privkey, $email); return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) . "' onclick=\"window.open('" . htmlentities ($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities ($emailparts [1]); } ?>
0x6a
trunk/application/helpers/recaptcha_helper.php
PHP
asf20
9,910
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
0x6a
trunk/application/helpers/index.html
HTML
asf20
114
<?php die('<!DOCTYPE html> <html lang="en"> <head> <title>Error Database</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> body{background: #ebebeb;font-family: dotum,tahoma} .error_contain{ padding: 0px; width: 500px; height: 350px; position: absolute; left: 50%; top: 50%; margin: -180px 0 0 -260px; } .error_contain h1{ font-family: arial; text-align: center; margin: 0; font-size: 169px; line-height: normal; color: #ffffff; text-shadow: 0 0 10px #ffffff, 0 4px 3px #ffffff, 0 9px 3px #dddddd, 0 12px 1px #cccccc, 0 14px 5px rgba(0, 0, 0, 0.2), 0 20px 10px rgba(0, 0, 0, 0.1), 0 15px 80px rgba(0, 0, 100, 0.2); } .error_contain h3{color: #777;margin: 0;padding: 8px;padding-top: 20px} .error_contain p{margin: 0;padding: 8px;color: #777;text-align: justify;font-size: 13px} </style> </head> <body> <div class="error_contain"> <h1 style="">Error</h1> <h3>'.$heading.'</h3> <p> '.$message.' </p> </div> </body> </html> ');
0x6a
trunk/application/errors/error_db.php
PHP
asf20
1,180
<!DOCTYPE html> <html lang="en"> <head> <title>404 Page Not Found</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> body{background: #ebebeb;font-family: dotum,tahoma} .error_contain{ padding: 0px; width: 500px; height: 350px; position: absolute; left: 50%; top: 50%; margin: -180px 0 0 -260px; } .error_contain h1{ font-family: arial; text-align: center; margin: 0; font-size: 169px; line-height: normal; color: #ffffff; text-shadow: 0 0 10px #ffffff, 0 4px 3px #ffffff, 0 9px 3px #dddddd, 0 12px 1px #cccccc, 0 14px 5px rgba(0, 0, 0, 0.2), 0 20px 10px rgba(0, 0, 0, 0.1), 0 15px 80px rgba(0, 0, 100, 0.2); } .error_contain h3{color: #777;margin: 0;padding: 8px;padding-top: 20px} .error_contain p{margin: 0;padding: 8px;color: #777;text-align: justify;font-size: 13px} </style> </head> <body> <div class="error_contain"> <h1 style="">404</h1> <h3>Whoops! Page not found...<span style="float: right">٩(๏̯͡๏)۶</span></h3> <p> Sorry, it appears the page you were looking for doesn't exist anymore or might have been moved. If the problem persists, please contact our support at example@domain.com. </p> </div> </body> </html>
0x6a
trunk/application/errors/error_404.php
Hack
asf20
1,395
<?php die('<!DOCTYPE html> <html lang="en"> <head> <title>Error general</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> body{background: #ebebeb;font-family: dotum,tahoma} .error_contain{ padding: 0px; width: 500px; height: 350px; position: absolute; left: 50%; top: 50%; margin: -180px 0 0 -260px; } .error_contain h1{ font-family: arial; text-align: center; margin: 0; font-size: 169px; line-height: normal; color: #ffffff; text-shadow: 0 0 10px #ffffff, 0 4px 3px #ffffff, 0 9px 3px #dddddd, 0 12px 1px #cccccc, 0 14px 5px rgba(0, 0, 0, 0.2), 0 20px 10px rgba(0, 0, 0, 0.1), 0 15px 80px rgba(0, 0, 100, 0.2); } .error_contain h3{color: #777;margin: 0;padding: 8px;padding-top: 20px} .error_contain p{margin: 0;padding: 8px;color: #777;text-align: justify;font-size: 13px} </style> </head> <body> <div class="error_contain"> <h1 style="">Error</h1> <h3>'.$heading.'</h3> <p> '.$message.' </p> </div> </body> </html> ');
0x6a
trunk/application/errors/error_general.php
PHP
asf20
1,179
<?php die('<!DOCTYPE html> <html lang="en"> <head> <title>A PHP Error was encountered</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> body{background: #ebebeb;font-family: dotum,tahoma} .error_contain{ padding: 0px; width: 500px; height: 350px; position: absolute; left: 50%; top: 50%; margin: -180px 0 0 -260px; } .error_contain h1{ font-family: arial; text-align: center; margin: 0; font-size: 169px; line-height: normal; color: #ffffff; text-shadow: 0 0 10px #ffffff, 0 4px 3px #ffffff, 0 9px 3px #dddddd, 0 12px 1px #cccccc, 0 14px 5px rgba(0, 0, 0, 0.2), 0 20px 10px rgba(0, 0, 0, 0.1), 0 15px 80px rgba(0, 0, 100, 0.2); } .error_contain h3{color: #777;margin: 0;padding: 8px;padding-top: 20px} .error_contain p{margin: 0;padding: 8px;color: #777;text-align: justify;font-size: 13px} </style> </head> <body> <div class="error_contain"> <h1 style="">Error</h1> <h3>A PHP Error was encountered</h3> <p> Severity: '.$severity.'</br> Message: '.$message.'</br> Filename: '.$filepath.'</br> Line Number: '.$line.' </p> </div> </body> </html> ');
0x6a
trunk/application/errors/error_php.php
PHP
asf20
1,330
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
0x6a
trunk/application/errors/index.html
HTML
asf20
114
<!DOCTYPE html> <html lang="en"> <head> <title>403 Request forbidden</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> body{background: #ebebeb;font-family: dotum,tahoma} .error_contain{ padding: 0px; width: 500px; height: 350px; position: absolute; left: 50%; top: 50%; margin: -180px 0 0 -260px; } .error_contain h1{ font-family: arial; text-align: center; margin: 0; font-size: 169px; line-height: normal; color: #ffffff; text-shadow: 0 0 10px #ffffff, 0 4px 3px #ffffff, 0 9px 3px #dddddd, 0 12px 1px #cccccc, 0 14px 5px rgba(0, 0, 0, 0.2), 0 20px 10px rgba(0, 0, 0, 0.1), 0 15px 80px rgba(0, 0, 100, 0.2); } .error_contain h3{color: #777;margin: 0;padding: 8px;padding-top: 20px} .error_contain p{margin: 0;padding: 8px;color: #777;text-align: justify;font-size: 13px} </style> </head> <body> <div class="error_contain"> <h1 style="">403</h1> <h3>Oops! Request forbidden...<span style="float: right">٩(๏̯͡๏)۶</span></h3> <p> Sorry, it appears the page you were looking for is forbidden and not accessible. If the problem persists, please contact our support at example@domain.com. </p> </div> </body> </html>
0x6a
trunk/application/errors/error_403.php
Hack
asf20
1,424
<!DOCTYPE html> <html lang="en"> <head> <title>403 Server error</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> body{background: #ebebeb;font-family: dotum,tahoma} .error_contain{ padding: 0px; width: 500px; height: 350px; position: absolute; left: 50%; top: 50%; margin: -180px 0 0 -260px; } .error_contain h1{ font-family: arial; text-align: center; margin: 0; font-size: 169px; line-height: normal; color: #ffffff; text-shadow: 0 0 10px #ffffff, 0 4px 3px #ffffff, 0 9px 3px #dddddd, 0 12px 1px #cccccc, 0 14px 5px rgba(0, 0, 0, 0.2), 0 20px 10px rgba(0, 0, 0, 0.1), 0 15px 80px rgba(0, 0, 100, 0.2); } .error_contain h3{color: #777;margin: 0;padding: 8px;padding-top: 20px} .error_contain p{margin: 0;padding: 8px;color: #777;text-align: justify;font-size: 13px} </style> </head> <body> <div class="error_contain"> <h1 style="">500</h1> <h3>Oops! Server error...<span style="float: right">٩(๏̯͡๏)۶</span></h3> <p> Sorry, it appears there has been an internal server error with the page you've requested If the problem persists, please contact our support at example@domain.com. </p> </div> </body> </html>
0x6a
trunk/application/errors/error_500.php
Hack
asf20
1,422
<?php /** * Vietnamese Version */ $PHPMAILER_LANG['provide_address'] = 'Bạn chưa nhập địa chỉ email người nhận!'; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer không được hỗ trợ.'; $PHPMAILER_LANG['execute'] = 'Không thể thực hiện: '; $PHPMAILER_LANG['instantiate'] = 'Không thể thực hiện hàm mail.'; $PHPMAILER_LANG['authenticate'] = 'Lỗi SMTP: Không thể chứng thực.'; $PHPMAILER_LANG['from_failed'] = 'Địa chỉ người gởi sai: '; $PHPMAILER_LANG['recipients_failed'] = 'Lỗi SMTP: Địa chỉ người nhận sai: '; $PHPMAILER_LANG['data_not_accepted'] = 'Lỗi SMTP: Dữ liệu không hợp lệ.'; $PHPMAILER_LANG['connect_host'] = 'Lỗi SMTP: Không kết nối được với SMTP host.'; $PHPMAILER_LANG['file_access'] = 'Không thể truy xuất file: '; $PHPMAILER_LANG['file_open'] = 'Lỗi File: Không thể mở file: '; $PHPMAILER_LANG['encoding'] = 'Lỗi encoding: '; $PHPMAILER_LANG['signing'] = 'Lỗi Signing: '; $PHPMAILER_LANG['smtp_error'] = 'Lỗi SMTP server: '; $PHPMAILER_LANG['empty_message'] = 'Nội dung rỗng'; $PHPMAILER_LANG['invalid_address'] = 'Địa chỉ không hợp lệ'; $PHPMAILER_LANG['variable_set'] = 'Không thể khởi tạo biến: ' ?>
0x6a
trunk/application/libraries/phpmailer/language/phpmailer.lang-vi.php
PHP
asf20
1,256
<?php /* ~ class.phpmailer.php .---------------------------------------------------------------------------. | Software: PHPMailer - PHP email class | | Version: 5.2.1 | | Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ | | ------------------------------------------------------------------------- | | Admin: Jim Jagielski (project admininistrator) | | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net | | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net | | : Jim Jagielski (jimjag) jimjag@gmail.com | | Founder: Brent R. Matzelle (original founder) | | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. | | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. | | Copyright (c) 2001-2003, Brent R. Matzelle | | ------------------------------------------------------------------------- | | License: Distributed under the Lesser General Public License (LGPL) | | http://www.gnu.org/copyleft/lesser.html | | This program is distributed in the hope that it will be useful - WITHOUT | | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | | FITNESS FOR A PARTICULAR PURPOSE. | '---------------------------------------------------------------------------' */ /** * PHPMailer - PHP email transport class * NOTE: Requires PHP version 5 or later * @package PHPMailer * @author Andy Prevost * @author Marcus Bointon * @author Jim Jagielski * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @version $Id: class.phpmailer.php 450 2010-06-23 16:46:33Z coolbru $ * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License */ if (version_compare(PHP_VERSION, '5.0.0', '<')) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n"); class PHPMailer { ///////////////////////////////////////////////// // PROPERTIES, PUBLIC ///////////////////////////////////////////////// /** * Email priority (1 = High, 3 = Normal, 5 = low). * @var int */ public $Priority = 3; /** * Sets the CharSet of the message. * @var string */ public $CharSet = 'iso-8859-1'; /** * Sets the Content-type of the message. * @var string */ public $ContentType = 'text/plain'; /** * Sets the Encoding of the message. Options for this are * "8bit", "7bit", "binary", "base64", and "quoted-printable". * @var string */ public $Encoding = '8bit'; /** * Holds the most recent mailer error message. * @var string */ public $ErrorInfo = ''; /** * Sets the From email address for the message. * @var string */ public $From = 'root@localhost'; /** * Sets the From name of the message. * @var string */ public $FromName = 'Root User'; /** * Sets the Sender email (Return-Path) of the message. If not empty, * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. * @var string */ public $Sender = ''; /** * Sets the Subject of the message. * @var string */ public $Subject = ''; /** * Sets the Body of the message. This can be either an HTML or text body. * If HTML then run IsHTML(true). * @var string */ public $Body = ''; /** * Sets the text-only body of the message. This automatically sets the * email to multipart/alternative. This body can be read by mail * clients that do not have HTML email capability such as mutt. Clients * that can read HTML will view the normal Body. * @var string */ public $AltBody = ''; /** * Stores the complete compiled MIME message body. * @var string * @access protected */ protected $MIMEBody = ''; /** * Stores the complete compiled MIME message headers. * @var string * @access protected */ protected $MIMEHeader = ''; /** * Stores the complete sent MIME message (Body and Headers) * @var string * @access protected */ protected $SentMIMEMessage = ''; /** * Sets word wrapping on the body of the message to a given number of * characters. * @var int */ public $WordWrap = 0; /** * Method to send mail: ("mail", "sendmail", or "smtp"). * @var string */ public $Mailer = 'mail'; /** * Sets the path of the sendmail program. * @var string */ public $Sendmail = '/usr/sbin/sendmail'; /** * Path to PHPMailer plugins. Useful if the SMTP class * is in a different directory than the PHP include path. * @var string */ public $PluginDir = ''; /** * Sets the email address that a reading confirmation will be sent. * @var string */ public $ConfirmReadingTo = ''; /** * Sets the hostname to use in Message-Id and Received headers * and as default HELO string. If empty, the value returned * by SERVER_NAME is used or 'localhost.localdomain'. * @var string */ public $Hostname = ''; /** * Sets the message ID to be used in the Message-Id header. * If empty, a unique id will be generated. * @var string */ public $MessageID = ''; ///////////////////////////////////////////////// // PROPERTIES FOR SMTP ///////////////////////////////////////////////// /** * Sets the SMTP hosts. All hosts must be separated by a * semicolon. You can also specify a different port * for each host by using this format: [hostname:port] * (e.g. "smtp1.example.com:25;smtp2.example.com"). * Hosts will be tried in order. * @var string */ public $Host = 'localhost'; /** * Sets the default SMTP server port. * @var int */ public $Port = 25; /** * Sets the SMTP HELO of the message (Default is $Hostname). * @var string */ public $Helo = ''; /** * Sets connection prefix. * Options are "", "ssl" or "tls" * @var string */ public $SMTPSecure = ''; /** * Sets SMTP authentication. Utilizes the Username and Password variables. * @var bool */ public $SMTPAuth = false; /** * Sets SMTP username. * @var string */ public $Username = ''; /** * Sets SMTP password. * @var string */ public $Password = ''; /** * Sets the SMTP server timeout in seconds. * This function will not work with the win32 version. * @var int */ public $Timeout = 10; /** * Sets SMTP class debugging on or off. * @var bool */ public $SMTPDebug = false; /** * Prevents the SMTP connection from being closed after each mail * sending. If this is set to true then to close the connection * requires an explicit call to SmtpClose(). * @var bool */ public $SMTPKeepAlive = false; /** * Provides the ability to have the TO field process individual * emails, instead of sending to entire TO addresses * @var bool */ public $SingleTo = false; /** * If SingleTo is true, this provides the array to hold the email addresses * @var bool */ public $SingleToArray = array(); /** * Provides the ability to change the line ending * @var string */ public $LE = "\n"; /** * Used with DKIM DNS Resource Record * @var string */ public $DKIM_selector = 'phpmailer'; /** * Used with DKIM DNS Resource Record * optional, in format of email address 'you@yourdomain.com' * @var string */ public $DKIM_identity = ''; /** * Used with DKIM DNS Resource Record * @var string */ public $DKIM_passphrase = ''; /** * Used with DKIM DNS Resource Record * optional, in format of email address 'you@yourdomain.com' * @var string */ public $DKIM_domain = ''; /** * Used with DKIM DNS Resource Record * optional, in format of email address 'you@yourdomain.com' * @var string */ public $DKIM_private = ''; /** * Callback Action function name * the function that handles the result of the send email action. Parameters: * bool $result result of the send action * string $to email address of the recipient * string $cc cc email addresses * string $bcc bcc email addresses * string $subject the subject * string $body the email body * @var string */ public $action_function = ''; //'callbackAction'; /** * Sets the PHPMailer Version number * @var string */ public $Version = '5.2.1'; /** * What to use in the X-Mailer header * @var string */ public $XMailer = ''; ///////////////////////////////////////////////// // PROPERTIES, PRIVATE AND PROTECTED ///////////////////////////////////////////////// protected $smtp = NULL; protected $to = array(); protected $cc = array(); protected $bcc = array(); protected $ReplyTo = array(); protected $all_recipients = array(); protected $attachment = array(); protected $CustomHeader = array(); protected $message_type = ''; protected $boundary = array(); protected $language = array(); protected $error_count = 0; protected $sign_cert_file = ''; protected $sign_key_file = ''; protected $sign_key_pass = ''; protected $exceptions = false; ///////////////////////////////////////////////// // CONSTANTS ///////////////////////////////////////////////// const STOP_MESSAGE = 0; // message only, continue processing const STOP_CONTINUE = 1; // message?, likely ok to continue processing const STOP_CRITICAL = 2; // message, plus full stop, critical error reached ///////////////////////////////////////////////// // METHODS, VARIABLES ///////////////////////////////////////////////// /** * Constructor * @param boolean $exceptions Should we throw external exceptions? */ public function __construct($exceptions = false) { $this->exceptions = ($exceptions == true); } /** * Sets message type to HTML. * @param bool $ishtml * @return void */ public function IsHTML($ishtml = true) { if ($ishtml) { $this->ContentType = 'text/html'; } else { $this->ContentType = 'text/plain'; } } /** * Sets Mailer to send message using SMTP. * @return void */ public function IsSMTP() { $this->Mailer = 'smtp'; } /** * Sets Mailer to send message using PHP mail() function. * @return void */ public function IsMail() { $this->Mailer = 'mail'; } /** * Sets Mailer to send message using the $Sendmail program. * @return void */ public function IsSendmail() { if (!stristr(ini_get('sendmail_path'), 'sendmail')) { $this->Sendmail = '/var/qmail/bin/sendmail'; } $this->Mailer = 'sendmail'; } /** * Sets Mailer to send message using the qmail MTA. * @return void */ public function IsQmail() { if (stristr(ini_get('sendmail_path'), 'qmail')) { $this->Sendmail = '/var/qmail/bin/sendmail'; } $this->Mailer = 'sendmail'; } ///////////////////////////////////////////////// // METHODS, RECIPIENTS ///////////////////////////////////////////////// /** * Adds a "To" address. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddAddress($address, $name = '') { return $this->AddAnAddress('to', $address, $name); } /** * Adds a "Cc" address. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddCC($address, $name = '') { return $this->AddAnAddress('cc', $address, $name); } /** * Adds a "Bcc" address. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddBCC($address, $name = '') { return $this->AddAnAddress('bcc', $address, $name); } /** * Adds a "Reply-to" address. * @param string $address * @param string $name * @return boolean */ public function AddReplyTo($address, $name = '') { return $this->AddAnAddress('Reply-To', $address, $name); } /** * Adds an address to one of the recipient arrays * Addresses that have been added already return false, but do not throw exceptions * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' * @param string $address The email address to send to * @param string $name * @return boolean true on success, false if address already used or invalid in some way * @access protected */ protected function AddAnAddress($kind, $address, $name = '') { if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) { $this->SetError($this->Lang('Invalid recipient array') . ': ' . $kind); if ($this->exceptions) { throw new phpmailerException('Invalid recipient array: ' . $kind); } if ($this->SMTPDebug) { echo $this->Lang('Invalid recipient array') . ': ' . $kind; } return false; } $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (!self::ValidateAddress($address)) { $this->SetError($this->Lang('invalid_address') . ': ' . $address); if ($this->exceptions) { throw new phpmailerException($this->Lang('invalid_address') . ': ' . $address); } if ($this->SMTPDebug) { echo $this->Lang('invalid_address') . ': ' . $address; } return false; } if ($kind != 'Reply-To') { if (!isset($this->all_recipients[strtolower($address)])) { array_push($this->$kind, array($address, $name)); $this->all_recipients[strtolower($address)] = true; return true; } } else { if (!array_key_exists(strtolower($address), $this->ReplyTo)) { $this->ReplyTo[strtolower($address)] = array($address, $name); return true; } } return false; } /** * Set the From and FromName properties * @param string $address * @param string $name * @return boolean */ public function SetFrom($address, $name = '', $auto = 1) { $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (!self::ValidateAddress($address)) { $this->SetError($this->Lang('invalid_address') . ': ' . $address); if ($this->exceptions) { throw new phpmailerException($this->Lang('invalid_address') . ': ' . $address); } if ($this->SMTPDebug) { echo $this->Lang('invalid_address') . ': ' . $address; } return false; } $this->From = $address; $this->FromName = $name; if ($auto) { if (empty($this->ReplyTo)) { $this->AddAnAddress('Reply-To', $address, $name); } if (empty($this->Sender)) { $this->Sender = $address; } } return true; } /** * Check that a string looks roughly like an email address should * Static so it can be used without instantiation * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator * Conforms approximately to RFC2822 * @link http://www.hexillion.com/samples/#Regex Original pattern found here * @param string $address The email address to check * @return boolean * @static * @access public */ public static function ValidateAddress($address) { if (function_exists('filter_var')) { //Introduced in PHP 5.2 if (filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) { return false; } else { return true; } } else { return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address); } } ///////////////////////////////////////////////// // METHODS, MAIL SENDING ///////////////////////////////////////////////// /** * Creates message and assigns Mailer. If the message is * not sent successfully then it returns false. Use the ErrorInfo * variable to view description of the error. * @return bool */ public function Send() { try { if (!$this->PreSend()) return false; return $this->PostSend(); } catch (phpmailerException $e) { $this->SentMIMEMessage = ''; $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } return false; } } protected function PreSend() { try { $mailHeader = ""; if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL); } // Set whether the message is multipart/alternative if (!empty($this->AltBody)) { $this->ContentType = 'multipart/alternative'; } $this->error_count = 0; // reset errors $this->SetMessageType(); //Refuse to send an empty message if (empty($this->Body)) { throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL); } $this->MIMEHeader = $this->CreateHeader(); $this->MIMEBody = $this->CreateBody(); // To capture the complete message when using mail(), create // an extra header list which CreateHeader() doesn't fold in if ($this->Mailer == 'mail') { if (count($this->to) > 0) { $mailHeader .= $this->AddrAppend("To", $this->to); } else { $mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;"); } $mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject)))); // if(count($this->cc) > 0) { // $mailHeader .= $this->AddrAppend("Cc", $this->cc); // } } // digitally sign with DKIM if enabled if ($this->DKIM_domain && $this->DKIM_private) { $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody); $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader; } $this->SentMIMEMessage = sprintf("%s%s\r\n\r\n%s", $this->MIMEHeader, $mailHeader, $this->MIMEBody); return true; } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } return false; } } protected function PostSend() { try { // Choose the mailer and send through it switch ($this->Mailer) { case 'sendmail': return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody); case 'smtp': return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody); case 'mail': return $this->MailSend($this->MIMEHeader, $this->MIMEBody); default: return $this->MailSend($this->MIMEHeader, $this->MIMEBody); } } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } if ($this->SMTPDebug) { echo $e->getMessage() . "\n"; } return false; } } /** * Sends mail using the $Sendmail program. * @param string $header The message headers * @param string $body The message body * @access protected * @return bool */ protected function SendmailSend($header, $body) { if ($this->Sender != '') { $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); } else { $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); } if ($this->SingleTo === true) { foreach ($this->SingleToArray as $key => $val) { if (!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, "To: " . $val . "\n"); fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); // implement call back function if it exists $isSent = ($result == 0) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); if ($result != 0) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } } else { if (!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); // implement call back function if it exists $isSent = ($result == 0) ? 1 : 0; $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body); if ($result != 0) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } return true; } /** * Sends mail using the PHP mail() function. * @param string $header The message headers * @param string $body The message body * @access protected * @return bool */ protected function MailSend($header, $body) { $toArr = array(); foreach ($this->to as $t) { $toArr[] = $this->AddrFormat($t); } $to = implode(', ', $toArr); if (empty($this->Sender)) { $params = "-oi "; } else { $params = sprintf("-oi -f %s", $this->Sender); } if ($this->Sender != '' and !ini_get('safe_mode')) { $old_from = ini_get('sendmail_from'); ini_set('sendmail_from', $this->Sender); if ($this->SingleTo === true && count($toArr) > 1) { foreach ($toArr as $key => $val) { $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); } } else { $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); } } else { if ($this->SingleTo === true && count($toArr) > 1) { foreach ($toArr as $key => $val) { $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); } } else { $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); } } if (isset($old_from)) { ini_set('sendmail_from', $old_from); } if (!$rt) { throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL); } return true; } /** * Sends mail via SMTP using PhpSMTP * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. * @param string $header The message headers * @param string $body The message body * @uses SMTP * @access protected * @return bool */ protected function SmtpSend($header, $body) { require_once $this->PluginDir . 'class.smtp.php'; $bad_rcpt = array(); if (!$this->SmtpConnect()) { throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL); } $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; if (!$this->smtp->Mail($smtp_from)) { throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL); } // Attempt to send attach all recipients foreach ($this->to as $to) { if (!$this->smtp->Recipient($to[0])) { $bad_rcpt[] = $to[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); } } foreach ($this->cc as $cc) { if (!$this->smtp->Recipient($cc[0])) { $bad_rcpt[] = $cc[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); } } foreach ($this->bcc as $bcc) { if (!$this->smtp->Recipient($bcc[0])) { $bad_rcpt[] = $bcc[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); } } if (count($bad_rcpt) > 0) { //Create error message for any bad addresses $badaddresses = implode(', ', $bad_rcpt); throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses); } if (!$this->smtp->Data($header . $body)) { throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL); } if ($this->SMTPKeepAlive == true) { $this->smtp->Reset(); } return true; } /** * Initiates a connection to an SMTP server. * Returns false if the operation failed. * @uses SMTP * @access public * @return bool */ public function SmtpConnect() { if (is_null($this->smtp)) { $this->smtp = new SMTP(); } $this->smtp->do_debug = $this->SMTPDebug; $hosts = explode(';', $this->Host); $index = 0; $connection = $this->smtp->Connected(); // Retry while there is no connection try { while ($index < count($hosts) && !$connection) { $hostinfo = array(); if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) { $host = $hostinfo[1]; $port = $hostinfo[2]; } else { $host = $hosts[$index]; $port = $this->Port; } $tls = ($this->SMTPSecure == 'tls'); $ssl = ($this->SMTPSecure == 'ssl'); if ($this->smtp->Connect(($ssl ? 'ssl://' : '') . $host, $port, $this->Timeout)) { $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname()); $this->smtp->Hello($hello); if ($tls) { if (!$this->smtp->StartTLS()) { throw new phpmailerException($this->Lang('tls')); } //We must resend HELO after tls negotiation $this->smtp->Hello($hello); } $connection = true; if ($this->SMTPAuth) { if (!$this->smtp->Authenticate($this->Username, $this->Password)) { throw new phpmailerException($this->Lang('authenticate')); } } } $index++; if (!$connection) { throw new phpmailerException($this->Lang('connect_host')); } } } catch (phpmailerException $e) { $this->smtp->Reset(); if ($this->exceptions) { throw $e; } } return true; } /** * Closes the active SMTP session if one exists. * @return void */ public function SmtpClose() { if (!is_null($this->smtp)) { if ($this->smtp->Connected()) { $this->smtp->Quit(); $this->smtp->Close(); } } } /** * Sets the language for all class error messages. * Returns false if it cannot load the language file. The default language is English. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br") * @param string $lang_path Path to the language file directory * @access public */ function SetLanguage($langcode = 'en', $lang_path = 'language/') { //Define full set of translatable strings $PHPMAILER_LANG = array( 'provide_address' => 'You must provide at least one recipient email address.', 'mailer_not_supported' => ' mailer is not supported.', 'execute' => 'Could not execute: ', 'instantiate' => 'Could not instantiate mail function.', 'authenticate' => 'SMTP Error: Could not authenticate.', 'from_failed' => 'The following From address failed: ', 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 'data_not_accepted' => 'SMTP Error: Data not accepted.', 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 'file_access' => 'Could not access file: ', 'file_open' => 'File Error: Could not open file: ', 'encoding' => 'Unknown encoding: ', 'signing' => 'Signing Error: ', 'smtp_error' => 'SMTP server error: ', 'empty_message' => 'Message body empty', 'invalid_address' => 'Invalid address', 'variable_set' => 'Cannot set or reset variable: ' ); //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"! $l = true; if ($langcode != 'en') { //There is no English translation file $l = @include $lang_path . 'phpmailer.lang-' . $langcode . '.php'; } $this->language = $PHPMAILER_LANG; return ($l == true); //Returns false if language not found } /** * Return the current array of language strings * @return array */ public function GetTranslations() { return $this->language; } ///////////////////////////////////////////////// // METHODS, MESSAGE CREATION ///////////////////////////////////////////////// /** * Creates recipient headers. * @access public * @return string */ public function AddrAppend($type, $addr) { $addr_str = $type . ': '; $addresses = array(); foreach ($addr as $a) { $addresses[] = $this->AddrFormat($a); } $addr_str .= implode(', ', $addresses); $addr_str .= $this->LE; return $addr_str; } /** * Formats an address correctly. * @access public * @return string */ public function AddrFormat($addr) { if (empty($addr[1])) { return $this->SecureHeader($addr[0]); } else { return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; } } /** * Wraps message for use with mailers that do not * automatically perform wrapping and for quoted-printable. * Original written by philippe. * @param string $message The message to wrap * @param integer $length The line length to wrap to * @param boolean $qp_mode Whether to run in Quoted-Printable mode * @access public * @return string */ public function WrapText($message, $length, $qp_mode = false) { $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; // If utf-8 encoding is used, we will need to make sure we don't // split multibyte characters when we wrap $is_utf8 = (strtolower($this->CharSet) == "utf-8"); $message = $this->FixEOL($message); if (substr($message, -1) == $this->LE) { $message = substr($message, 0, -1); } $line = explode($this->LE, $message); $message = ''; for ($i = 0; $i < count($line); $i++) { $line_part = explode(' ', $line[$i]); $buf = ''; for ($e = 0; $e < count($line_part); $e++) { $word = $line_part[$e]; if ($qp_mode and (strlen($word) > $length)) { $space_left = $length - strlen($buf) - 1; if ($e != 0) { if ($space_left > 20) { $len = $space_left; if ($is_utf8) { $len = $this->UTF8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == "=") { $len--; } elseif (substr($word, $len - 2, 1) == "=") { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); $buf .= ' ' . $part; $message .= $buf . sprintf("=%s", $this->LE); } else { $message .= $buf . $soft_break; } $buf = ''; } while (strlen($word) > 0) { $len = $length; if ($is_utf8) { $len = $this->UTF8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == "=") { $len--; } elseif (substr($word, $len - 2, 1) == "=") { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); if (strlen($word) > 0) { $message .= $part . sprintf("=%s", $this->LE); } else { $buf = $part; } } } else { $buf_o = $buf; $buf .= ($e == 0) ? $word : (' ' . $word); if (strlen($buf) > $length and $buf_o != '') { $message .= $buf_o . $soft_break; $buf = $word; } } } $message .= $buf . $this->LE; } return $message; } /** * Finds last character boundary prior to maxLength in a utf-8 * quoted (printable) encoded string. * Original written by Colin Brown. * @access public * @param string $encodedText utf-8 QP text * @param int $maxLength find last character boundary prior to this length * @return int */ public function UTF8CharBoundary($encodedText, $maxLength) { $foundSplitPos = false; $lookBack = 3; while (!$foundSplitPos) { $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); $encodedCharPos = strpos($lastChunk, "="); if ($encodedCharPos !== false) { // Found start of encoded character byte within $lookBack block. // Check the encoded byte value (the 2 chars after the '=') $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); $dec = hexdec($hex); if ($dec < 128) { // Single byte character. // If the encoded char was found at pos 0, it will fit // otherwise reduce maxLength to start of the encoded char $maxLength = ($encodedCharPos == 0) ? $maxLength : $maxLength - ($lookBack - $encodedCharPos); $foundSplitPos = true; } elseif ($dec >= 192) { // First byte of a multi byte character // Reduce maxLength to split at start of character $maxLength = $maxLength - ($lookBack - $encodedCharPos); $foundSplitPos = true; } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back $lookBack += 3; } } else { // No encoded character found $foundSplitPos = true; } } return $maxLength; } /** * Set the body wrapping. * @access public * @return void */ public function SetWordWrap() { if ($this->WordWrap < 1) { return; } switch ($this->message_type) { case 'alt': case 'alt_inline': case 'alt_attach': case 'alt_inline_attach': $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); break; default: $this->Body = $this->WrapText($this->Body, $this->WordWrap); break; } } /** * Assembles message header. * @access public * @return string The assembled header */ public function CreateHeader() { $result = ''; // Set the boundaries $uniq_id = md5(uniqid(time())); $this->boundary[1] = 'b1_' . $uniq_id; $this->boundary[2] = 'b2_' . $uniq_id; $this->boundary[3] = 'b3_' . $uniq_id; $result .= $this->HeaderLine('Date', self::RFCDate()); if ($this->Sender == '') { $result .= $this->HeaderLine('Return-Path', trim($this->From)); } else { $result .= $this->HeaderLine('Return-Path', trim($this->Sender)); } // To be created automatically by mail() if ($this->Mailer != 'mail') { if ($this->SingleTo === true) { foreach ($this->to as $t) { $this->SingleToArray[] = $this->AddrFormat($t); } } else { if (count($this->to) > 0) { $result .= $this->AddrAppend('To', $this->to); } elseif (count($this->cc) == 0) { $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); } } } $from = array(); $from[0][0] = trim($this->From); $from[0][1] = $this->FromName; $result .= $this->AddrAppend('From', $from); // sendmail and mail() extract Cc from the header before sending if (count($this->cc) > 0) { $result .= $this->AddrAppend('Cc', $this->cc); } // sendmail and mail() extract Bcc from the header before sending if ((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { $result .= $this->AddrAppend('Bcc', $this->bcc); } if (count($this->ReplyTo) > 0) { $result .= $this->AddrAppend('Reply-To', $this->ReplyTo); } // mail() sets the subject itself if ($this->Mailer != 'mail') { $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); } if ($this->MessageID != '') { $result .= $this->HeaderLine('Message-ID', $this->MessageID); } else { $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); } $result .= $this->HeaderLine('X-Priority', $this->Priority); if ($this->XMailer) { $result .= $this->HeaderLine('X-Mailer', $this->XMailer); } else { $result .= $this->HeaderLine('X-Mailer', 'PHPMailer ' . $this->Version . ' (http://code.google.com/a/apache-extras.org/p/phpmailer/)'); } if ($this->ConfirmReadingTo != '') { $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); } // Add custom headers for ($index = 0; $index < count($this->CustomHeader); $index++) { $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); } if (!$this->sign_key_file) { $result .= $this->HeaderLine('MIME-Version', '1.0'); $result .= $this->GetMailMIME(); } return $result; } /** * Returns the message MIME. * @access public * @return string */ public function GetMailMIME() { $result = ''; switch ($this->message_type) { case 'plain': $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); $result .= $this->TextLine('Content-Type: ' . $this->ContentType . '; charset="' . $this->CharSet . '"'); break; case 'inline': $result .= $this->HeaderLine('Content-Type', 'multipart/related;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); break; case 'attach': case 'inline_attach': case 'alt_attach': case 'alt_inline_attach': $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); break; case 'alt': case 'alt_inline': $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); break; } if ($this->Mailer != 'mail') { $result .= $this->LE . $this->LE; } return $result; } /** * Returns the MIME message (headers and body). Only really valid post PreSend(). * @access public * @return string */ public function GetSentMIMEMessage() { return $this->SentMIMEMessage; } /** * Assembles the message body. Returns an empty string on failure. * @access public * @return string The assembled message body */ public function CreateBody() { $body = ''; if ($this->sign_key_file) { $body .= $this->GetMailMIME(); } $this->SetWordWrap(); switch ($this->message_type) { case 'plain': $body .= $this->EncodeString($this->Body, $this->Encoding); break; case 'inline': $body .= $this->GetBoundary($this->boundary[1], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->AttachAll("inline", $this->boundary[1]); break; case 'attach': $body .= $this->GetBoundary($this->boundary[1], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; case 'inline_attach': $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->AttachAll("inline", $this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; case 'alt': $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->EndBoundary($this->boundary[1]); break; case 'alt_inline': $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->AttachAll("inline", $this->boundary[2]); $body .= $this->LE; $body .= $this->EndBoundary($this->boundary[1]); break; case 'alt_attach': $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->EndBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; case 'alt_inline_attach': $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->TextLine("--" . $this->boundary[2]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE . $this->LE; $body .= $this->AttachAll("inline", $this->boundary[3]); $body .= $this->LE; $body .= $this->EndBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; } if ($this->IsError()) { $body = ''; } elseif ($this->sign_key_file) { try { $file = tempnam('', 'mail'); file_put_contents($file, $body); //TODO check this worked $signed = tempnam("", "signed"); if (@openssl_pkcs7_sign($file, $signed, "file://" . $this->sign_cert_file, array("file://" . $this->sign_key_file, $this->sign_key_pass), NULL)) { @unlink($file); $body = file_get_contents($signed); @unlink($signed); } else { @unlink($file); @unlink($signed); throw new phpmailerException($this->Lang("signing") . openssl_error_string()); } } catch (phpmailerException $e) { $body = ''; if ($this->exceptions) { throw $e; } } } return $body; } /** * Returns the start of a message boundary. * @access protected * @return string */ protected function GetBoundary($boundary, $charSet, $contentType, $encoding) { $result = ''; if ($charSet == '') { $charSet = $this->CharSet; } if ($contentType == '') { $contentType = $this->ContentType; } if ($encoding == '') { $encoding = $this->Encoding; } $result .= $this->TextLine('--' . $boundary); $result .= sprintf("Content-Type: %s; charset=\"%s\"", $contentType, $charSet); $result .= $this->LE; $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); $result .= $this->LE; return $result; } /** * Returns the end of a message boundary. * @access protected * @return string */ protected function EndBoundary($boundary) { return $this->LE . '--' . $boundary . '--' . $this->LE; } /** * Sets the message type. * @access protected * @return void */ protected function SetMessageType() { $this->message_type = array(); if ($this->AlternativeExists()) $this->message_type[] = "alt"; if ($this->InlineImageExists()) $this->message_type[] = "inline"; if ($this->AttachmentExists()) $this->message_type[] = "attach"; $this->message_type = implode("_", $this->message_type); if ($this->message_type == "") $this->message_type = "plain"; } /** * Returns a formatted header line. * @access public * @return string */ public function HeaderLine($name, $value) { return $name . ': ' . $value . $this->LE; } /** * Returns a formatted mail line. * @access public * @return string */ public function TextLine($value) { return $value . $this->LE; } ///////////////////////////////////////////////// // CLASS METHODS, ATTACHMENTS ///////////////////////////////////////////////// /** * Adds an attachment from a path on the filesystem. * Returns false if the file could not be found * or accessed. * @param string $path Path to the attachment. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return bool */ public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { try { if (!@is_file($path)) { throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE); } $filename = basename($path); if ($name == '') { $name = $filename; } $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => 'attachment', 7 => 0 ); } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } if ($this->SMTPDebug) { echo $e->getMessage() . "\n"; } if ($e->getCode() == self::STOP_CRITICAL) { return false; } } return true; } /** * Return the current array of attachments * @return array */ public function GetAttachments() { return $this->attachment; } /** * Attaches all fs, string, and binary attachments to the message. * Returns an empty string on failure. * @access protected * @return string */ protected function AttachAll($disposition_type, $boundary) { // Return text of body $mime = array(); $cidUniq = array(); $incl = array(); // Add all attachments foreach ($this->attachment as $attachment) { // CHECK IF IT IS A VALID DISPOSITION_FILTER if ($attachment[6] == $disposition_type) { // Check for string attachment $bString = $attachment[5]; if ($bString) { $string = $attachment[0]; } else { $path = $attachment[0]; } $inclhash = md5(serialize($attachment)); if (in_array($inclhash, $incl)) { continue; } $incl[] = $inclhash; $filename = $attachment[1]; $name = $attachment[2]; $encoding = $attachment[3]; $type = $attachment[4]; $disposition = $attachment[6]; $cid = $attachment[7]; if ($disposition == 'inline' && isset($cidUniq[$cid])) { continue; } $cidUniq[$cid] = true; $mime[] = sprintf("--%s%s", $boundary, $this->LE); $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); if ($disposition == 'inline') { $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); } $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE . $this->LE); // Encode as string attachment if ($bString) { $mime[] = $this->EncodeString($string, $encoding); if ($this->IsError()) { return ''; } $mime[] = $this->LE . $this->LE; } else { $mime[] = $this->EncodeFile($path, $encoding); if ($this->IsError()) { return ''; } $mime[] = $this->LE . $this->LE; } } } $mime[] = sprintf("--%s--%s", $boundary, $this->LE); return implode("", $mime); } /** * Encodes attachment in requested format. * Returns an empty string on failure. * @param string $path The full path to the file * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @see EncodeFile() * @access protected * @return string */ protected function EncodeFile($path, $encoding = 'base64') { try { if (!is_readable($path)) { throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE); } if (function_exists('get_magic_quotes')) { function get_magic_quotes() { return false; } } $magic_quotes = get_magic_quotes_runtime(); if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime(0); } else { ini_set('magic_quotes_runtime', 0); } } $file_buffer = file_get_contents($path); $file_buffer = $this->EncodeString($file_buffer, $encoding); if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime($magic_quotes); } else { ini_set('magic_quotes_runtime', $magic_quotes); } } return $file_buffer; } catch (Exception $e) { $this->SetError($e->getMessage()); return ''; } } /** * Encodes string to requested format. * Returns an empty string on failure. * @param string $str The text to encode * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @access public * @return string */ public function EncodeString($str, $encoding = 'base64') { $encoded = ''; switch (strtolower($encoding)) { case 'base64': $encoded = chunk_split(base64_encode($str), 76, $this->LE); break; case '7bit': case '8bit': $encoded = $this->FixEOL($str); //Make sure it ends with a line break if (substr($encoded, -(strlen($this->LE))) != $this->LE) $encoded .= $this->LE; break; case 'binary': $encoded = $str; break; case 'quoted-printable': $encoded = $this->EncodeQP($str); break; default: $this->SetError($this->Lang('encoding') . $encoding); break; } return $encoded; } /** * Encode a header string to best (shortest) of Q, B, quoted or none. * @access public * @return string */ public function EncodeHeader($str, $position = 'text') { $x = 0; switch (strtolower($position)) { case 'phrase': if (!preg_match('/[\200-\377]/', $str)) { // Can't use addslashes as we don't know what value has magic_quotes_sybase $encoded = addcslashes($str, "\0..\37\177\\\""); if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { return ($encoded); } else { return ("\"$encoded\""); } } $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); break; case 'comment': $x = preg_match_all('/[()"]/', $str, $matches); // Fall-through case 'text': default: $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); break; } if ($x == 0) { return ($str); } $maxlen = 75 - 7 - strlen($this->CharSet); // Try to select the encoding which should produce the shortest output if (strlen($str) / 3 < $x) { $encoding = 'B'; if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { // Use a custom function which correctly encodes and wraps long // multibyte strings without breaking lines within a character $encoded = $this->Base64EncodeWrapMB($str); } else { $encoded = base64_encode($str); $maxlen -= $maxlen % 4; $encoded = trim(chunk_split($encoded, $maxlen, "\n")); } } else { $encoding = 'Q'; $encoded = $this->EncodeQ($str, $position); $encoded = $this->WrapText($encoded, $maxlen, true); $encoded = str_replace('=' . $this->LE, "\n", trim($encoded)); } $encoded = preg_replace('/^(.*)$/m', " =?" . $this->CharSet . "?$encoding?\\1?=", $encoded); $encoded = trim(str_replace("\n", $this->LE, $encoded)); return $encoded; } /** * Checks if a string contains multibyte characters. * @access public * @param string $str multi-byte text to wrap encode * @return bool */ public function HasMultiBytes($str) { if (function_exists('mb_strlen')) { return (strlen($str) > mb_strlen($str, $this->CharSet)); } else { // Assume no multibytes (we can't handle without mbstring functions anyway) return false; } } /** * Correctly encodes and wraps long multibyte strings for mail headers * without breaking lines within a character. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php * @access public * @param string $str multi-byte text to wrap encode * @return string */ public function Base64EncodeWrapMB($str) { $start = "=?" . $this->CharSet . "?B?"; $end = "?="; $encoded = ""; $mb_length = mb_strlen($str, $this->CharSet); // Each line must have length <= 75, including $start and $end $length = 75 - strlen($start) - strlen($end); // Average multi-byte ratio $ratio = $mb_length / strlen($str); // Base64 has a 4:3 ratio $offset = $avgLength = floor($length * $ratio * .75); for ($i = 0; $i < $mb_length; $i += $offset) { $lookBack = 0; do { $offset = $avgLength - $lookBack; $chunk = mb_substr($str, $i, $offset, $this->CharSet); $chunk = base64_encode($chunk); $lookBack++; } while (strlen($chunk) > $length); $encoded .= $chunk . $this->LE; } // Chomp the last linefeed $encoded = substr($encoded, 0, -strlen($this->LE)); return $encoded; } /** * Encode string to quoted-printable. * Only uses standard PHP, slow, but will always work * @access public * @param string $string the text to encode * @param integer $line_max Number of chars allowed on a line before wrapping * @return string */ public function EncodeQPphp($input = '', $line_max = 76, $space_conv = false) { $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); $lines = preg_split('/(?:\r\n|\r|\n)/', $input); $eol = "\r\n"; $escape = '='; $output = ''; while (list(, $line) = each($lines)) { $linlen = strlen($line); $newline = ''; for ($i = 0; $i < $linlen; $i++) { $c = substr($line, $i, 1); $dec = ord($c); if (( $i == 0 ) && ( $dec == 46 )) { // convert first point in the line into =2E $c = '=2E'; } if ($dec == 32) { if ($i == ( $linlen - 1 )) { // convert space at eol only $c = '=20'; } else if ($space_conv) { $c = '=20'; } } elseif (($dec == 61) || ($dec < 32 ) || ($dec > 126)) { // always encode "\t", which is *not* required $h2 = floor($dec / 16); $h1 = floor($dec % 16); $c = $escape . $hex[$h2] . $hex[$h1]; } if ((strlen($newline) + strlen($c)) >= $line_max) { // CRLF is not counted $output .= $newline . $escape . $eol; // soft line break; " =\r\n" is okay $newline = ''; // check if newline first character will be point or not if ($dec == 46) { $c = '=2E'; } } $newline .= $c; } // end of for $output .= $newline . $eol; } // end of while return $output; } /** * Encode string to RFC2045 (6.7) quoted-printable format * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version * Also results in same content as you started with after decoding * @see EncodeQPphp() * @access public * @param string $string the text to encode * @param integer $line_max Number of chars allowed on a line before wrapping * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function * @return string * @author Marcus Bointon */ public function EncodeQP($string, $line_max = 76, $space_conv = false) { if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) return quoted_printable_encode($string); } $filters = stream_get_filters(); if (!in_array('convert.*', $filters)) { //Got convert stream filter? return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation } $fp = fopen('php://temp/', 'r+'); $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE); $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params); fputs($fp, $string); rewind($fp); $out = stream_get_contents($fp); stream_filter_remove($s); $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange fclose($fp); return $out; } /** * Encode string to q encoding. * @link http://tools.ietf.org/html/rfc2047 * @param string $str the text to encode * @param string $position Where the text is going to be used, see the RFC for what that means * @access public * @return string */ public function EncodeQ($str, $position = 'text') { // There should not be any EOL in the string $encoded = preg_replace('/[\r\n]*/', '', $str); switch (strtolower($position)) { case 'phrase': $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); break; case 'comment': $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); case 'text': default: // Replace every high ascii, control =, ? and _ characters //TODO using /e (equivalent to eval()) is probably not a good idea $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e', "'='.sprintf('%02X', ord(stripslashes('\\1')))", $encoded); break; } // Replace every spaces to _ (more readable than =20) $encoded = str_replace(' ', '_', $encoded); return $encoded; } /** * Adds a string or binary attachment (non-filesystem) to the list. * This method can be used to attach ascii or binary data, * such as a BLOB record from a database. * @param string $string String attachment data. * @param string $filename Name of the attachment. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return void */ public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') { // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $filename, 2 => basename($filename), 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => 'attachment', 7 => 0 ); } /** * Adds an embedded attachment. This can include images, sounds, and * just about any other document. Make sure to set the $type to an * image type. For JPEG images use "image/jpeg" and for GIF images * use "image/gif". * @param string $path Path to the attachment. * @param string $cid Content ID of the attachment. Use this to identify * the Id for accessing the image in an HTML form. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return bool */ public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { if (!@is_file($path)) { $this->SetError($this->Lang('file_access') . $path); return false; } $filename = basename($path); if ($name == '') { $name = $filename; } // Append to $attachment array $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => 'inline', 7 => $cid ); return true; } public function AddStringEmbeddedImage($string, $cid, $filename = '', $encoding = 'base64', $type = 'application/octet-stream') { // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $filename, 2 => basename($filename), 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => 'inline', 7 => $cid ); } /** * Returns true if an inline attachment is present. * @access public * @return bool */ public function InlineImageExists() { foreach ($this->attachment as $attachment) { if ($attachment[6] == 'inline') { return true; } } return false; } public function AttachmentExists() { foreach ($this->attachment as $attachment) { if ($attachment[6] == 'attachment') { return true; } } return false; } public function AlternativeExists() { return strlen($this->AltBody) > 0; } ///////////////////////////////////////////////// // CLASS METHODS, MESSAGE RESET ///////////////////////////////////////////////// /** * Clears all recipients assigned in the TO array. Returns void. * @return void */ public function ClearAddresses() { foreach ($this->to as $to) { unset($this->all_recipients[strtolower($to[0])]); } $this->to = array(); } /** * Clears all recipients assigned in the CC array. Returns void. * @return void */ public function ClearCCs() { foreach ($this->cc as $cc) { unset($this->all_recipients[strtolower($cc[0])]); } $this->cc = array(); } /** * Clears all recipients assigned in the BCC array. Returns void. * @return void */ public function ClearBCCs() { foreach ($this->bcc as $bcc) { unset($this->all_recipients[strtolower($bcc[0])]); } $this->bcc = array(); } /** * Clears all recipients assigned in the ReplyTo array. Returns void. * @return void */ public function ClearReplyTos() { $this->ReplyTo = array(); } /** * Clears all recipients assigned in the TO, CC and BCC * array. Returns void. * @return void */ public function ClearAllRecipients() { $this->to = array(); $this->cc = array(); $this->bcc = array(); $this->all_recipients = array(); } /** * Clears all previously set filesystem, string, and binary * attachments. Returns void. * @return void */ public function ClearAttachments() { $this->attachment = array(); } /** * Clears all custom headers. Returns void. * @return void */ public function ClearCustomHeaders() { $this->CustomHeader = array(); } ///////////////////////////////////////////////// // CLASS METHODS, MISCELLANEOUS ///////////////////////////////////////////////// /** * Adds the error message to the error container. * @access protected * @return void */ protected function SetError($msg) { $this->error_count++; if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { $lasterror = $this->smtp->getError(); if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n"; } } $this->ErrorInfo = $msg; } /** * Returns the proper RFC 822 formatted date. * @access public * @return string * @static */ public static function RFCDate() { $tz = date('Z'); $tzs = ($tz < 0) ? '-' : '+'; $tz = abs($tz); $tz = (int) ($tz / 3600) * 100 + ($tz % 3600) / 60; $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz); return $result; } /** * Returns the server hostname or 'localhost.localdomain' if unknown. * @access protected * @return string */ protected function ServerHostname() { if (!empty($this->Hostname)) { $result = $this->Hostname; } elseif (isset($_SERVER['SERVER_NAME'])) { $result = $_SERVER['SERVER_NAME']; } else { $result = 'localhost.localdomain'; } return $result; } /** * Returns a message in the appropriate language. * @access protected * @return string */ protected function Lang($key) { if (count($this->language) < 1) { $this->SetLanguage('en'); // set the default language } if (isset($this->language[$key])) { return $this->language[$key]; } else { return 'Language string failed to load: ' . $key; } } /** * Returns true if an error occurred. * @access public * @return bool */ public function IsError() { return ($this->error_count > 0); } /** * Changes every end of line from CR or LF to CRLF. * @access public * @return string */ public function FixEOL($str) { $str = str_replace("\r\n", "\n", $str); $str = str_replace("\r", "\n", $str); $str = str_replace("\n", $this->LE, $str); return $str; } /** * Adds a custom header. * @access public * @return void */ public function AddCustomHeader($custom_header) { $this->CustomHeader[] = explode(':', $custom_header, 2); } /** * Evaluates the message and returns modifications for inline images and backgrounds * @access public * @return $message */ public function MsgHTML($message, $basedir = '') { preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images); if (isset($images[2])) { foreach ($images[2] as $i => $url) { // do not change urls for absolute images (thanks to corvuscorax) if (!preg_match('#^[A-z]+://#', $url)) { $filename = basename($url); $directory = dirname($url); ($directory == '.') ? $directory = '' : ''; $cid = 'cid:' . md5($filename); $ext = pathinfo($filename, PATHINFO_EXTENSION); $mimeType = self::_mime_types($ext); if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; } if (strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; } if ($this->AddEmbeddedImage($basedir . $directory . $filename, md5($filename), $filename, 'base64', $mimeType)) { $message = preg_replace("/" . $images[1][$i] . "=[\"']" . preg_quote($url, '/') . "[\"']/Ui", $images[1][$i] . "=\"" . $cid . "\"", $message); } } } } $this->IsHTML(true); $this->Body = $message; if (empty($this->AltBody)) { $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message))); if (!empty($textMsg)) { $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet); } } if (empty($this->AltBody)) { $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; } return $message; } /** * Gets the MIME type of the embedded or inline image * @param string File extension * @access public * @return string MIME type of ext * @static */ public static function _mime_types($ext = '') { $mimes = array( 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'doc' => 'application/msword', '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/octet-stream', 'so' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'gtar' => 'application/x-gtar', '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' => 'application/zip', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mpga' => 'audio/mpeg', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', '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' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/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' => 'text/plain', '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', 'word' => 'application/msword', 'xl' => 'application/excel', 'eml' => 'message/rfc822' ); return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; } /** * Set (or reset) Class Objects (variables) * * Usage Example: * $page->set('X-Priority', '3'); * * @access public * @param string $name Parameter Name * @param mixed $value Parameter Value * NOTE: will not work with arrays, there are no arrays to set/reset * @todo Should this not be using __set() magic function? */ public function set($name, $value = '') { try { if (isset($this->$name)) { $this->$name = $value; } else { throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL); } } catch (Exception $e) { $this->SetError($e->getMessage()); if ($e->getCode() == self::STOP_CRITICAL) { return false; } } return true; } /** * Strips newlines to prevent header injection. * @access public * @param string $str String * @return string */ public function SecureHeader($str) { $str = str_replace("\r", '', $str); $str = str_replace("\n", '', $str); return trim($str); } /** * Set the private key file and password to sign the message. * * @access public * @param string $key_filename Parameter File Name * @param string $key_pass Password for private key */ public function Sign($cert_filename, $key_filename, $key_pass) { $this->sign_cert_file = $cert_filename; $this->sign_key_file = $key_filename; $this->sign_key_pass = $key_pass; } /** * Set the private key file and password to sign the message. * * @access public * @param string $key_filename Parameter File Name * @param string $key_pass Password for private key */ public function DKIM_QP($txt) { $tmp = ''; $line = ''; for ($i = 0; $i < strlen($txt); $i++) { $ord = ord($txt[$i]); if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { $line .= $txt[$i]; } else { $line .= "=" . sprintf("%02X", $ord); } } return $line; } /** * Generate DKIM signature * * @access public * @param string $s Header */ public function DKIM_Sign($s) { $privKeyStr = file_get_contents($this->DKIM_private); if ($this->DKIM_passphrase != '') { $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); } else { $privKey = $privKeyStr; } if (openssl_sign($s, $signature, $privKey)) { return base64_encode($signature); } } /** * Generate DKIM Canonicalization Header * * @access public * @param string $s Header */ public function DKIM_HeaderC($s) { $s = preg_replace("/\r\n\s+/", " ", $s); $lines = explode("\r\n", $s); foreach ($lines as $key => $line) { list($heading, $value) = explode(":", $line, 2); $heading = strtolower($heading); $value = preg_replace("/\s+/", " ", $value); // Compress useless spaces $lines[$key] = $heading . ":" . trim($value); // Don't forget to remove WSP around the value } $s = implode("\r\n", $lines); return $s; } /** * Generate DKIM Canonicalization Body * * @access public * @param string $body Message Body */ public function DKIM_BodyC($body) { if ($body == '') return "\r\n"; // stabilize line endings $body = str_replace("\r\n", "\n", $body); $body = str_replace("\n", "\r\n", $body); // END stabilize line endings while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { $body = substr($body, 0, strlen($body) - 2); } return $body; } /** * Create the DKIM header, body, as new header * * @access public * @param string $headers_line Header lines * @param string $subject Subject * @param string $body Body */ public function DKIM_Add($headers_line, $subject, $body) { $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body $DKIMquery = 'dns/txt'; // Query method $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) $subject_header = "Subject: $subject"; $headers = explode($this->LE, $headers_line); foreach ($headers as $header) { if (strpos($header, 'From:') === 0) { $from_header = $header; } elseif (strpos($header, 'To:') === 0) { $to_header = $header; } } $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)); // Copied header fields (dkim-quoted-printable $body = $this->DKIM_BodyC($body); $DKIMlen = strlen($body); // Length of body $DKIMb64 = base64_encode(pack("H*", sha1($body))); // Base64 of packed binary SHA-1 hash of body $ident = ($this->DKIM_identity == '') ? '' : " i=" . $this->DKIM_identity . ";"; $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n" . "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n" . "\th=From:To:Subject;\r\n" . "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n" . "\tz=$from\r\n" . "\t|$to\r\n" . "\t|$subject;\r\n" . "\tbh=" . $DKIMb64 . ";\r\n" . "\tb="; $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs); $signed = $this->DKIM_Sign($toSign); return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n" . $dkimhdrs . $signed . "\r\n"; } protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body) { if (!empty($this->action_function) && function_exists($this->action_function)) { $params = array($isSent, $to, $cc, $bcc, $subject, $body); call_user_func_array($this->action_function, $params); } } } class phpmailerException extends Exception { public function errorMessage() { $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n"; return $errorMsg; } } ?>
0x6a
trunk/application/libraries/phpmailer/class.phpmailer.php
PHP
asf20
92,042
<?php /* ~ class.smtp.php .---------------------------------------------------------------------------. | Software: PHPMailer - PHP email class | | Version: 5.2.1 | | Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ | | ------------------------------------------------------------------------- | | Admin: Jim Jagielski (project admininistrator) | | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net | | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net | | : Jim Jagielski (jimjag) jimjag@gmail.com | | Founder: Brent R. Matzelle (original founder) | | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. | | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. | | Copyright (c) 2001-2003, Brent R. Matzelle | | ------------------------------------------------------------------------- | | License: Distributed under the Lesser General Public License (LGPL) | | http://www.gnu.org/copyleft/lesser.html | | This program is distributed in the hope that it will be useful - WITHOUT | | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | | FITNESS FOR A PARTICULAR PURPOSE. | '---------------------------------------------------------------------------' */ /** * PHPMailer - PHP SMTP email transport class * NOTE: Designed for use with PHP version 5 and up * @package PHPMailer * @author Andy Prevost * @author Marcus Bointon * @copyright 2004 - 2008 Andy Prevost * @author Jim Jagielski * @copyright 2010 - 2012 Jim Jagielski * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) * @version $Id: class.smtp.php 450 2010-06-23 16:46:33Z coolbru $ */ /** * SMTP is rfc 821 compliant and implements all the rfc 821 SMTP * commands except TURN which will always return a not implemented * error. SMTP also provides some utility methods for sending mail * to an SMTP server. * original author: Chris Ryan */ class SMTP { /** * SMTP server port * @var int */ public $SMTP_PORT = 25; /** * SMTP reply line ending * @var string */ public $CRLF = "\r\n"; /** * Sets whether debugging is turned on * @var bool */ public $do_debug; // the level of debug to perform /** * Sets VERP use on/off (default is off) * @var bool */ public $do_verp = false; /** * Sets the SMTP PHPMailer Version number * @var string */ public $Version = '5.2.1'; ///////////////////////////////////////////////// // PROPERTIES, PRIVATE AND PROTECTED ///////////////////////////////////////////////// private $smtp_conn; // the socket to the server private $error; // error if any on the last call private $helo_rply; // the reply the server sent to us for HELO /** * Initialize the class so that the data is in a known state. * @access public * @return void */ public function __construct() { $this->smtp_conn = 0; $this->error = null; $this->helo_rply = null; $this->do_debug = 0; } ///////////////////////////////////////////////// // CONNECTION FUNCTIONS ///////////////////////////////////////////////// /** * Connect to the server specified on the port specified. * If the port is not specified use the default SMTP_PORT. * If tval is specified then a connection will try and be * established with the server for that number of seconds. * If tval is not specified the default is 30 seconds to * try on the connection. * * SMTP CODE SUCCESS: 220 * SMTP CODE FAILURE: 421 * @access public * @return bool */ public function Connect($host, $port = 0, $tval = 30) { // set the error val to null so there is no confusion $this->error = null; // make sure we are __not__ connected if ($this->connected()) { // already connected, generate error $this->error = array("error" => "Already connected to a server"); return false; } if (empty($port)) { $port = $this->SMTP_PORT; } // connect to the smtp server $this->smtp_conn = @fsockopen($host, // the host of the server $port, // the port to use $errno, // error number if any $errstr, // error message if any $tval); // give up after ? secs // verify we connected properly if (empty($this->smtp_conn)) { $this->error = array("error" => "Failed to connect to server", "errno" => $errno, "errstr" => $errstr); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />'; } return false; } // SMTP server can take longer to respond, give longer timeout for first read // Windows does not have support for this timeout function if (substr(PHP_OS, 0, 3) != "WIN") socket_set_timeout($this->smtp_conn, $tval, 0); // get any announcement $announce = $this->get_lines(); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />'; } return true; } /** * Initiate a TLS communication with the server. * * SMTP CODE 220 Ready to start TLS * SMTP CODE 501 Syntax error (no parameters allowed) * SMTP CODE 454 TLS not available due to temporary reason * @access public * @return bool success */ public function StartTLS() { $this->error = null; # to avoid confusion if (!$this->connected()) { $this->error = array("error" => "Called StartTLS() without being connected"); return false; } fputs($this->smtp_conn, "STARTTLS" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if ($code != 220) { $this->error = array("error" => "STARTTLS not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } // Begin encrypted connection if (!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { return false; } return true; } /** * Performs SMTP authentication. Must be run after running the * Hello() method. Returns true if successfully authenticated. * @access public * @return bool */ public function Authenticate($username, $password) { // Start authentication fputs($this->smtp_conn, "AUTH LOGIN" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($code != 334) { $this->error = array("error" => "AUTH not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } // Send encoded username fputs($this->smtp_conn, base64_encode($username) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($code != 334) { $this->error = array("error" => "Username not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } // Send encoded password fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($code != 235) { $this->error = array("error" => "Password not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Returns true if connected to a server otherwise false * @access public * @return bool */ public function Connected() { if (!empty($this->smtp_conn)) { $sock_status = socket_get_status($this->smtp_conn); if ($sock_status["eof"]) { // the socket is valid but we are not connected if ($this->do_debug >= 1) { echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; } $this->Close(); return false; } return true; // everything looks good } return false; } /** * Closes the socket and cleans up the state of the class. * It is not considered good to use this function without * first trying to use QUIT. * @access public * @return void */ public function Close() { $this->error = null; // so there is no confusion $this->helo_rply = null; if (!empty($this->smtp_conn)) { // close the connection and cleanup fclose($this->smtp_conn); $this->smtp_conn = 0; } } ///////////////////////////////////////////////// // SMTP COMMANDS ///////////////////////////////////////////////// /** * Issues a data command and sends the msg_data to the server * finializing the mail transaction. $msg_data is the message * that is to be send with the headers. Each header needs to be * on a single line followed by a <CRLF> with the message headers * and the message body being seperated by and additional <CRLF>. * * Implements rfc 821: DATA <CRLF> * * SMTP CODE INTERMEDIATE: 354 * [data] * <CRLF>.<CRLF> * SMTP CODE SUCCESS: 250 * SMTP CODE FAILURE: 552,554,451,452 * SMTP CODE FAILURE: 451,554 * SMTP CODE ERROR : 500,501,503,421 * @access public * @return bool */ public function Data($msg_data) { $this->error = null; // so no confusion is caused if (!$this->connected()) { $this->error = array( "error" => "Called Data() without being connected"); return false; } fputs($this->smtp_conn, "DATA" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if ($code != 354) { $this->error = array("error" => "DATA command not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } /* the server is ready to accept data! * according to rfc 821 we should not send more than 1000 * including the CRLF * characters on a single line so we will break the data up * into lines by \r and/or \n then if needed we will break * each of those into smaller lines to fit within the limit. * in addition we will be looking for lines that start with * a period '.' and append and additional period '.' to that * line. NOTE: this does not count towards limit. */ // normalize the line breaks so we know the explode works $msg_data = str_replace("\r\n", "\n", $msg_data); $msg_data = str_replace("\r", "\n", $msg_data); $lines = explode("\n", $msg_data); /* we need to find a good way to determine is headers are * in the msg_data or if it is a straight msg body * currently I am assuming rfc 822 definitions of msg headers * and if the first field of the first line (':' sperated) * does not contain a space then it _should_ be a header * and we can process all lines before a blank "" line as * headers. */ $field = substr($lines[0], 0, strpos($lines[0], ":")); $in_headers = false; if (!empty($field) && !strstr($field, " ")) { $in_headers = true; } $max_line_length = 998; // used below; set here for ease in change while (list(, $line) = @each($lines)) { $lines_out = null; if ($line == "" && $in_headers) { $in_headers = false; } // ok we need to break this line up into several smaller lines while (strlen($line) > $max_line_length) { $pos = strrpos(substr($line, 0, $max_line_length), " "); // Patch to fix DOS attack if (!$pos) { $pos = $max_line_length - 1; $lines_out[] = substr($line, 0, $pos); $line = substr($line, $pos); } else { $lines_out[] = substr($line, 0, $pos); $line = substr($line, $pos + 1); } /* if processing headers add a LWSP-char to the front of new line * rfc 822 on long msg headers */ if ($in_headers) { $line = "\t" . $line; } } $lines_out[] = $line; // send the lines to the server while (list(, $line_out) = @each($lines_out)) { if (strlen($line_out) > 0) { if (substr($line_out, 0, 1) == ".") { $line_out = "." . $line_out; } } fputs($this->smtp_conn, $line_out . $this->CRLF); } } // message data has been sent fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if ($code != 250) { $this->error = array("error" => "DATA not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Sends the HELO command to the smtp server. * This makes sure that we and the server are in * the same known state. * * Implements from rfc 821: HELO <SP> <domain> <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE ERROR : 500, 501, 504, 421 * @access public * @return bool */ public function Hello($host = '') { $this->error = null; // so no confusion is caused if (!$this->connected()) { $this->error = array( "error" => "Called Hello() without being connected"); return false; } // if hostname for HELO was not specified send default if (empty($host)) { // determine appropriate default to send to server $host = "localhost"; } // Send extended hello first (RFC 2821) if (!$this->SendHello("EHLO", $host)) { if (!$this->SendHello("HELO", $host)) { return false; } } return true; } /** * Sends a HELO/EHLO command. * @access private * @return bool */ private function SendHello($hello, $host) { fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '<br />'; } if ($code != 250) { $this->error = array("error" => $hello . " not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } $this->helo_rply = $rply; return true; } /** * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. * * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552,451,452 * SMTP CODE SUCCESS: 500,501,421 * @access public * @return bool */ public function Mail($from) { $this->error = null; // so no confusion is caused if (!$this->connected()) { $this->error = array( "error" => "Called Mail() without being connected"); return false; } $useVerp = ($this->do_verp ? "XVERP" : ""); fputs($this->smtp_conn, "MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if ($code != 250) { $this->error = array("error" => "MAIL not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Sends the quit command to the server and then closes the socket * if there is no error or the $close_on_error argument is true. * * Implements from rfc 821: QUIT <CRLF> * * SMTP CODE SUCCESS: 221 * SMTP CODE ERROR : 500 * @access public * @return bool */ public function Quit($close_on_error = true) { $this->error = null; // so there is no confusion if (!$this->connected()) { $this->error = array( "error" => "Called Quit() without being connected"); return false; } // send the quit command to the server fputs($this->smtp_conn, "quit" . $this->CRLF); // get any good-bye messages $byemsg = $this->get_lines(); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />'; } $rval = true; $e = null; $code = substr($byemsg, 0, 3); if ($code != 221) { // use e as a tmp var cause Close will overwrite $this->error $e = array("error" => "SMTP server rejected quit command", "smtp_code" => $code, "smtp_rply" => substr($byemsg, 4)); $rval = false; if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />'; } } if (empty($e) || $close_on_error) { $this->Close(); } return $rval; } /** * Sends the command RCPT to the SMTP server with the TO: argument of $to. * Returns true if the recipient was accepted false if it was rejected. * * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF> * * SMTP CODE SUCCESS: 250,251 * SMTP CODE FAILURE: 550,551,552,553,450,451,452 * SMTP CODE ERROR : 500,501,503,421 * @access public * @return bool */ public function Recipient($to) { $this->error = null; // so no confusion is caused if (!$this->connected()) { $this->error = array( "error" => "Called Recipient() without being connected"); return false; } fputs($this->smtp_conn, "RCPT TO:<" . $to . ">" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if ($code != 250 && $code != 251) { $this->error = array("error" => "RCPT not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Sends the RSET command to abort and transaction that is * currently in progress. Returns true if successful false * otherwise. * * Implements rfc 821: RSET <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE ERROR : 500,501,504,421 * @access public * @return bool */ public function Reset() { $this->error = null; // so no confusion is caused if (!$this->connected()) { $this->error = array( "error" => "Called Reset() without being connected"); return false; } fputs($this->smtp_conn, "RSET" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if ($code != 250) { $this->error = array("error" => "RSET failed", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. This command * will send the message to the users terminal if they are logged * in and send them an email. * * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552,451,452 * SMTP CODE SUCCESS: 500,501,502,421 * @access public * @return bool */ public function SendAndMail($from) { $this->error = null; // so no confusion is caused if (!$this->connected()) { $this->error = array( "error" => "Called SendAndMail() without being connected"); return false; } fputs($this->smtp_conn, "SAML FROM:" . $from . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if ($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if ($code != 250) { $this->error = array("error" => "SAML not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply, 4)); if ($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * This is an optional command for SMTP that this class does not * support. This method is here to make the RFC821 Definition * complete for this class and __may__ be implimented in the future * * Implements from rfc 821: TURN <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE FAILURE: 502 * SMTP CODE ERROR : 500, 503 * @access public * @return bool */ public function Turn() { $this->error = array("error" => "This method, TURN, of the SMTP " . "is not implemented"); if ($this->do_debug >= 1) { echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />'; } return false; } /** * Get the current error * @access public * @return array */ public function getError() { return $this->error; } ///////////////////////////////////////////////// // INTERNAL FUNCTIONS ///////////////////////////////////////////////// /** * Read in as many lines as possible * either before eof or socket timeout occurs on the operation. * With SMTP we can tell if we have more lines to read if the * 4th character is '-' symbol. If it is a space then we don't * need to read anything else. * @access private * @return string */ private function get_lines() { $data = ""; while (!feof($this->smtp_conn)) { $str = @fgets($this->smtp_conn, 515); if ($this->do_debug >= 4) { echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />'; echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />'; } $data .= $str; if ($this->do_debug >= 4) { echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />'; } // if 4th character is a space, we are done reading, break the loop if (substr($str, 3, 1) == " ") { break; } } return $data; } } ?>
0x6a
trunk/application/libraries/phpmailer/class.smtp.php
PHP
asf20
27,480
<?php /* ~ class.pop3.php .---------------------------------------------------------------------------. | Software: PHPMailer - PHP email class | | Version: 5.2.1 | | Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ | | ------------------------------------------------------------------------- | | Admin: Jim Jagielski (project admininistrator) | | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net | | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net | | : Jim Jagielski (jimjag) jimjag@gmail.com | | Founder: Brent R. Matzelle (original founder) | | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. | | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. | | Copyright (c) 2001-2003, Brent R. Matzelle | | ------------------------------------------------------------------------- | | License: Distributed under the Lesser General Public License (LGPL) | | http://www.gnu.org/copyleft/lesser.html | | This program is distributed in the hope that it will be useful - WITHOUT | | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | | FITNESS FOR A PARTICULAR PURPOSE. | '---------------------------------------------------------------------------' */ /** * PHPMailer - PHP POP Before SMTP Authentication Class * NOTE: Designed for use with PHP version 5 and up * @package PHPMailer * @author Andy Prevost * @author Marcus Bointon * @author Jim Jagielski * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) * @version $Id: class.pop3.php 450 2010-06-23 16:46:33Z coolbru $ */ /** * POP Before SMTP Authentication Class * Version 5.2.1 * * Author: Richard Davey (rich@corephp.co.uk) * Modifications: Andy Prevost * License: LGPL, see PHPMailer License * * Specifically for PHPMailer to allow POP before SMTP authentication. * Does not yet work with APOP - if you have an APOP account, contact Richard Davey * and we can test changes to this script. * * This class is based on the structure of the SMTP class originally authored by Chris Ryan * * This class is rfc 1939 compliant and implements all the commands * required for POP3 connection, authentication and disconnection. * * @package PHPMailer * @author Richard Davey */ class POP3 { /** * Default POP3 port * @var int */ public $POP3_PORT = 110; /** * Default Timeout * @var int */ public $POP3_TIMEOUT = 30; /** * POP3 Carriage Return + Line Feed * @var string */ public $CRLF = "\r\n"; /** * Displaying Debug warnings? (0 = now, 1+ = yes) * @var int */ public $do_debug = 2; /** * POP3 Mail Server * @var string */ public $host; /** * POP3 Port * @var int */ public $port; /** * POP3 Timeout Value * @var int */ public $tval; /** * POP3 Username * @var string */ public $username; /** * POP3 Password * @var string */ public $password; /** * Sets the POP3 PHPMailer Version number * @var string */ public $Version = '5.2.1'; ///////////////////////////////////////////////// // PROPERTIES, PRIVATE AND PROTECTED ///////////////////////////////////////////////// private $pop_conn; private $connected; private $error; // Error log array /** * Constructor, sets the initial values * @access public * @return POP3 */ public function __construct() { $this->pop_conn = 0; $this->connected = false; $this->error = null; } /** * Combination of public events - connect, login, disconnect * @access public * @param string $host * @param integer $port * @param integer $tval * @param string $username * @param string $password */ public function Authorise($host, $port = false, $tval = false, $username, $password, $debug_level = 0) { $this->host = $host; // If no port value is passed, retrieve it if ($port == false) { $this->port = $this->POP3_PORT; } else { $this->port = $port; } // If no port value is passed, retrieve it if ($tval == false) { $this->tval = $this->POP3_TIMEOUT; } else { $this->tval = $tval; } $this->do_debug = $debug_level; $this->username = $username; $this->password = $password; // Refresh the error log $this->error = null; // Connect $result = $this->Connect($this->host, $this->port, $this->tval); if ($result) { $login_result = $this->Login($this->username, $this->password); if ($login_result) { $this->Disconnect(); return true; } } // We need to disconnect regardless if the login succeeded $this->Disconnect(); return false; } /** * Connect to the POP3 server * @access public * @param string $host * @param integer $port * @param integer $tval * @return boolean */ public function Connect($host, $port = false, $tval = 30) { // Are we already connected? if ($this->connected) { return true; } /* On Windows this will raise a PHP Warning error if the hostname doesn't exist. Rather than supress it with @fsockopen, let's capture it cleanly instead */ set_error_handler(array(&$this, 'catchWarning')); // Connect to the POP3 server $this->pop_conn = fsockopen($host, // POP3 Host $port, // Port # $errno, // Error Number $errstr, // Error Message $tval); // Timeout (seconds) // Restore the error handler restore_error_handler(); // Does the Error Log now contain anything? if ($this->error && $this->do_debug >= 1) { $this->displayErrors(); } // Did we connect? if ($this->pop_conn == false) { // It would appear not... $this->error = array( 'error' => "Failed to connect to server $host on port $port", 'errno' => $errno, 'errstr' => $errstr ); if ($this->do_debug >= 1) { $this->displayErrors(); } return false; } // Increase the stream time-out // Check for PHP 4.3.0 or later if (version_compare(phpversion(), '5.0.0', 'ge')) { stream_set_timeout($this->pop_conn, $tval, 0); } else { // Does not work on Windows if (substr(PHP_OS, 0, 3) !== 'WIN') { socket_set_timeout($this->pop_conn, $tval, 0); } } // Get the POP3 server response $pop3_response = $this->getResponse(); // Check for the +OK if ($this->checkResponse($pop3_response)) { // The connection is established and the POP3 server is talking $this->connected = true; return true; } } /** * Login to the POP3 server (does not support APOP yet) * @access public * @param string $username * @param string $password * @return boolean */ public function Login($username = '', $password = '') { if ($this->connected == false) { $this->error = 'Not connected to POP3 server'; if ($this->do_debug >= 1) { $this->displayErrors(); } } if (empty($username)) { $username = $this->username; } if (empty($password)) { $password = $this->password; } $pop_username = "USER $username" . $this->CRLF; $pop_password = "PASS $password" . $this->CRLF; // Send the Username $this->sendString($pop_username); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { // Send the Password $this->sendString($pop_password); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { return true; } else { return false; } } else { return false; } } /** * Disconnect from the POP3 server * @access public */ public function Disconnect() { $this->sendString('QUIT'); fclose($this->pop_conn); } ///////////////////////////////////////////////// // Private Methods ///////////////////////////////////////////////// /** * Get the socket response back. * $size is the maximum number of bytes to retrieve * @access private * @param integer $size * @return string */ private function getResponse($size = 128) { $pop3_response = fgets($this->pop_conn, $size); return $pop3_response; } /** * Send a string down the open socket connection to the POP3 server * @access private * @param string $string * @return integer */ private function sendString($string) { $bytes_sent = fwrite($this->pop_conn, $string, strlen($string)); return $bytes_sent; } /** * Checks the POP3 server response for +OK or -ERR * @access private * @param string $string * @return boolean */ private function checkResponse($string) { if (substr($string, 0, 3) !== '+OK') { $this->error = array( 'error' => "Server reported an error: $string", 'errno' => 0, 'errstr' => '' ); if ($this->do_debug >= 1) { $this->displayErrors(); } return false; } else { return true; } } /** * If debug is enabled, display the error message array * @access private */ private function displayErrors() { echo '<pre>'; foreach ($this->error as $single_error) { print_r($single_error); } echo '</pre>'; } /** * Takes over from PHP for the socket warning handler * @access private * @param integer $errno * @param string $errstr * @param string $errfile * @param integer $errline */ private function catchWarning($errno, $errstr, $errfile, $errline) { $this->error[] = array( 'error' => "Connecting to the POP3 server raised a PHP warning: ", 'errno' => $errno, 'errstr' => $errstr ); } // End of class } ?>
0x6a
trunk/application/libraries/phpmailer/class.pop3.php
PHP
asf20
11,383
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /* * This class is written based entirely on the work found below * www.techbytes.co.in/blogs/2006/01/15/consuming-rss-with-php-the-simple-way/ * All credit should be given to the original author * * Example: $this->load->library('rssparser'); $this->rssparser->set_feed_url('http://example.com/feed'); $this->rssparser->set_cache_life(30); $rss = $this->rssparser->getFeed(6); // Get six items from the feed // Using a callback function to parse addictional XML fields $this->load->library('rssparser', array($this, 'parseFile')); // parseFile method of current class function parseFile($data, $item) { $data['summary'] = (string)$item->summary; return $data; } */ class RSSParser { public $feed_uri = NULL; // Feed URI public $data = FALSE; // Associative array containing all the feed items public $channel_data = array(); // Store RSS Channel Data in an array public $feed_unavailable = NULL; // Boolean variable which indicates whether an RSS feed was unavailable public $cache_life = 0; // Cache lifetime public $cache_dir = './application/cache/'; // Cache directory public $write_cache_flag = FALSE; // Flag to write to cache public $callback = FALSE; // Callback to read custom data function __construct($callback = FALSE) { if ($callback) { $this->callback = $callback; } } // -------------------------------------------------------------------- function parse() { // Are we caching? if ($this->cache_life != 0) { $filename = $this->cache_dir.'rss_Parse_'.md5($this->feed_uri); // Is there a cache file ? if (file_exists($filename)) { // Has it expired? $timedif = (time() - filemtime($filename)); if ($timedif < ( $this->cache_life * 60)) { $rawFeed = file_get_contents($filename); } else { // So raise the falg $this->write_cache_flag = true; } } else { // Raise the flag to write the cache $this->write_cache_flag = true; } } // Reset $this->data = array(); $this->channel_data = array(); // Parse the document if (!isset($rawFeed)) { $rawFeed = file_get_contents($this->feed_uri); } $xml = new SimpleXmlElement($rawFeed); if ($xml->channel) { // Assign the channel data $this->channel_data['title'] = $xml->channel->title; $this->channel_data['description'] = $xml->channel->description; // Build the item array foreach ($xml->channel->item as $item) { $data = array(); $data['title'] = (string)$item->title; $data['description'] = (string)$item->description; $data['pubDate'] = (string)$item->pubDate; $data['link'] = (string)$item->link; $dc = $item->children('http://purl.org/dc/elements/1.1/'); $data['author'] = (string)$dc->creator; if ($this->callback) { $data = call_user_func($this->callback, $data, $item); } $this->data[] = $data; } } else { // Assign the channel data $this->channel_data['title'] = $xml->title; $this->channel_data['description'] = $xml->subtitle; // Build the item array foreach ($xml->entry as $item) { $data = array(); $data['id'] = (string)$item->id; $data['title'] = (string)$item->title; $data['description'] = (string)$item->content; $data['pubDate'] = (string)$item->published; $data['link'] = (string)$item->link['href']; $dc = $item->children('http://purl.org/dc/elements/1.1/'); $data['author'] = (string)$dc->creator; if ($this->callback) { $data = call_user_func($this->callback, $data, $item); } $this->data[] = $data; } } // Do we need to write the cache file? if ($this->write_cache_flag) { if (!$fp = @fopen($filename, 'wb')) { echo "RSSParser error"; log_message('error', "Unable to write cache file: ".$filename); return; } flock($fp, LOCK_EX); fwrite($fp, $rawFeed); flock($fp, LOCK_UN); fclose($fp); } return TRUE; } // -------------------------------------------------------------------- function set_cache_life($period = NULL) { $this->cache_life = $period; return $this; } // -------------------------------------------------------------------- function set_feed_url($url = NULL) { $this->feed_uri = $url; return $this; } // -------------------------------------------------------------------- /* Return the feeds one at a time: when there are no more feeds return false * @param No of items to return from the feed * @return Associative array of items */ function getFeed($num) { $this->parse(); $c = 0; $return = array(); foreach ($this->data AS $item) { $return[] = $item; $c++; if ($c == $num) { break; } } return $return; } // -------------------------------------------------------------------- /* Return channel data for the feed */ function & getChannelData() { $flag = false; if (!empty($this->channel_data)) { return $this->channel_data; } else { return $flag; } } // -------------------------------------------------------------------- /* Were we unable to retreive the feeds ? */ function errorInResponse() { return $this->feed_unavailable; } // -------------------------------------------------------------------- /* Initialize the feed data */ function clear() { $this->feed_uri = NULL; $this->data = FALSE; $this->channel_data = array(); $this->cache_life = 0; $this->callback = FALSE; return $this; } } /* End of file RSSParser.php */ /* Location: ./application/libraries/RSSParser.php */
0x6a
trunk/application/libraries/Rssparser.php
PHP
asf20
5,975
<?php # # This is a test program for the portable PHP password hashing framework. # # Written by Solar Designer and placed in the public domain. # See PasswordHash.php for more information. # require "PasswordHash.php"; header("Content-type: text/plain"); $ok = 0; # Try to use stronger but system-specific hashes, with a possible fallback to # the weaker portable hashes. $t_hasher = new PasswordHash(8, FALSE); $correct = "test12345"; $hash = $t_hasher->HashPassword($correct); print "Hash: " . $hash . "\n"; $check = $t_hasher->CheckPassword($correct, $hash); if ($check) $ok++; print "Check correct: '" . $check . "' (should be '1')\n"; $wrong = "test12346"; $check = $t_hasher->CheckPassword($wrong, $hash); if (!$check) $ok++; print "Check wrong: '" . $check . "' (should be '0' or '')\n"; unset($t_hasher); # Force the use of weaker portable hashes. $t_hasher = new PasswordHash(8, TRUE); $hash = $t_hasher->HashPassword($correct); print "Hash: " . $hash . "\n"; $check = $t_hasher->CheckPassword($correct, $hash); if ($check) $ok++; print "Check correct: '" . $check . "' (should be '1')\n"; $check = $t_hasher->CheckPassword($wrong, $hash); if (!$check) $ok++; print "Check wrong: '" . $check . "' (should be '0' or '')\n"; # A correct portable hash for "test12345". # Please note the use of single quotes to ensure that the dollar signs will # be interpreted literally. Of course, a real application making use of the # framework won't store password hashes within a PHP source file anyway. # We only do this for testing. $hash = '$P$9IQRaTwmfeRo7ud9Fh4E2PdI0S3r.L0'; print "Hash: " . $hash . "\n"; $check = $t_hasher->CheckPassword($correct, $hash); if ($check) $ok++; print "Check correct: '" . $check . "' (should be '1')\n"; $check = $t_hasher->CheckPassword($wrong, $hash); if (!$check) $ok++; print "Check wrong: '" . $check . "' (should be '0' or '')\n"; if ($ok == 6) print "All tests have PASSED\n"; else print "Some tests have FAILED\n"; ?>
0x6a
trunk/application/libraries/phpass-0.1/test.php
PHP
asf20
1,984
# # Written by Solar Designer and placed in the public domain. # See crypt_private.c for more information. # CC = gcc LD = $(CC) RM = rm -f CFLAGS = -Wall -O2 -fomit-frame-pointer -funroll-loops LDFLAGS = -s LIBS = -lcrypto all: crypt_private-test crypt_private-test: crypt_private-test.o $(LD) $(LDFLAGS) $(LIBS) crypt_private-test.o -o $@ crypt_private-test.o: crypt_private.c $(CC) -c $(CFLAGS) crypt_private.c -DTEST -o $@ clean: $(RM) crypt_private-test*
0x6a
trunk/application/libraries/phpass-0.1/c/Makefile
Makefile
asf20
467
/* * This code exists for the sole purpose to serve as another implementation * of the "private" password hashing method implemened in PasswordHash.php * and thus to confirm that these password hashes are indeed calculated as * intended. * * Other uses of this code are discouraged. There are much better password * hashing algorithms available to C programmers; one of those is bcrypt: * * http://www.openwall.com/crypt/ * * Written by Solar Designer <solar at openwall.com> in 2005 and placed in * the public domain. * * There's absolutely no warranty. */ #include <string.h> #include <openssl/md5.h> #ifdef TEST #include <stdio.h> #endif static char *itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static void encode64(char *dst, char *src, int count) { int i, value; i = 0; do { value = (unsigned char)src[i++]; *dst++ = itoa64[value & 0x3f]; if (i < count) value |= (unsigned char)src[i] << 8; *dst++ = itoa64[(value >> 6) & 0x3f]; if (i++ >= count) break; if (i < count) value |= (unsigned char)src[i] << 16; *dst++ = itoa64[(value >> 12) & 0x3f]; if (i++ >= count) break; *dst++ = itoa64[(value >> 18) & 0x3f]; } while (i < count); } char *crypt_private(char *password, char *setting) { static char output[32]; MD5_CTX ctx; char hash[MD5_DIGEST_LENGTH]; char *p, *salt; int count_log2, length, count; strcpy(output, "*0"); if (!strncmp(setting, output, 2)) output[1] = '1'; if (strncmp(setting, "$P$", 3)) return output; p = strchr(itoa64, setting[3]); if (!p) return output; count_log2 = p - itoa64; if (count_log2 < 7 || count_log2 > 31) return output; salt = setting + 4; if (strlen(salt) < 8) return output; length = strlen(password); MD5_Init(&ctx); MD5_Update(&ctx, salt, 8); MD5_Update(&ctx, password, length); MD5_Final(hash, &ctx); count = 1 << count_log2; do { MD5_Init(&ctx); MD5_Update(&ctx, hash, MD5_DIGEST_LENGTH); MD5_Update(&ctx, password, length); MD5_Final(hash, &ctx); } while (--count); memcpy(output, setting, 12); encode64(&output[12], hash, MD5_DIGEST_LENGTH); return output; } #ifdef TEST int main(int argc, char **argv) { if (argc != 3) return 1; puts(crypt_private(argv[1], argv[2])); return 0; } #endif
0x6a
trunk/application/libraries/phpass-0.1/c/crypt_private.c
C
asf20
2,283
<?php # # Portable PHP password hashing framework. # # Version 0.1 / genuine. # # Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in # the public domain. # # There's absolutely no warranty. # # The homepage URL for this framework is: # # http://www.openwall.com/phpass/ # # Please be sure to update the Version line if you edit this file in any way. # It is suggested that you leave the main version number intact, but indicate # your project name (after the slash) and add your own revision information. # # Please do not change the "private" password hashing method implemented in # here, thereby making your hashes incompatible. However, if you must, please # change the hash type identifier (the "$P$") to something different. # # Obviously, since this code is in the public domain, the above are not # requirements (there can be none), but merely suggestions. # class PasswordHash { var $itoa64; var $iteration_count_log2; var $portable_hashes; var $random_state; function PasswordHash($iteration_count_log2, $portable_hashes) { $this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) $iteration_count_log2 = 8; $this->iteration_count_log2 = $iteration_count_log2; $this->portable_hashes = $portable_hashes; $this->random_state = microtime() . getmypid(); } function get_random_bytes($count) { $output = ''; if (($fh = @fopen('/dev/urandom', 'rb'))) { $output = fread($fh, $count); fclose($fh); } if (strlen($output) < $count) { $output = ''; for ($i = 0; $i < $count; $i += 16) { $this->random_state = md5(microtime() . $this->random_state); $output .= pack('H*', md5($this->random_state)); } $output = substr($output, 0, $count); } return $output; } function encode64($input, $count) { $output = ''; $i = 0; do { $value = ord($input[$i++]); $output .= $this->itoa64[$value & 0x3f]; if ($i < $count) $value |= ord($input[$i]) << 8; $output .= $this->itoa64[($value >> 6) & 0x3f]; if ($i++ >= $count) break; if ($i < $count) $value |= ord($input[$i]) << 16; $output .= $this->itoa64[($value >> 12) & 0x3f]; if ($i++ >= $count) break; $output .= $this->itoa64[($value >> 18) & 0x3f]; } while ($i < $count); return $output; } function gensalt_private($input) { $output = '$P$'; $output .= $this->itoa64[min($this->iteration_count_log2 + ((PHP_VERSION >= '5') ? 5 : 3), 30)]; $output .= $this->encode64($input, 6); return $output; } function crypt_private($password, $setting) { $output = '*0'; if (substr($setting, 0, 2) == $output) $output = '*1'; if (substr($setting, 0, 3) != '$P$') return $output; $count_log2 = strpos($this->itoa64, $setting[3]); if ($count_log2 < 7 || $count_log2 > 30) return $output; $count = 1 << $count_log2; $salt = substr($setting, 4, 8); if (strlen($salt) != 8) return $output; # We're kind of forced to use MD5 here since it's the only # cryptographic primitive available in all versions of PHP # currently in use. To implement our own low-level crypto # in PHP would result in much worse performance and # consequently in lower iteration counts and hashes that are # quicker to crack (by non-PHP code). if (PHP_VERSION >= '5') { $hash = md5($salt . $password, TRUE); do { $hash = md5($hash . $password, TRUE); } while (--$count); } else { $hash = pack('H*', md5($salt . $password)); do { $hash = pack('H*', md5($hash . $password)); } while (--$count); } $output = substr($setting, 0, 12); $output .= $this->encode64($hash, 16); return $output; } function gensalt_extended($input) { $count_log2 = min($this->iteration_count_log2 + 8, 24); # This should be odd to not reveal weak DES keys, and the # maximum valid value is (2**24 - 1) which is odd anyway. $count = (1 << $count_log2) - 1; $output = '_'; $output .= $this->itoa64[$count & 0x3f]; $output .= $this->itoa64[($count >> 6) & 0x3f]; $output .= $this->itoa64[($count >> 12) & 0x3f]; $output .= $this->itoa64[($count >> 18) & 0x3f]; $output .= $this->encode64($input, 3); return $output; } function gensalt_blowfish($input) { # This one needs to use a different order of characters and a # different encoding scheme from the one in encode64() above. # We care because the last character in our encoded string will # only represent 2 bits. While two known implementations of # bcrypt will happily accept and correct a salt string which # has the 4 unused bits set to non-zero, we do not want to take # chances and we also do not want to waste an additional byte # of entropy. $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $output = '$2a$'; $output .= chr(ord('0') + $this->iteration_count_log2 / 10); $output .= chr(ord('0') + $this->iteration_count_log2 % 10); $output .= '$'; $i = 0; do { $c1 = ord($input[$i++]); $output .= $itoa64[$c1 >> 2]; $c1 = ($c1 & 0x03) << 4; if ($i >= 16) { $output .= $itoa64[$c1]; break; } $c2 = ord($input[$i++]); $c1 |= $c2 >> 4; $output .= $itoa64[$c1]; $c1 = ($c2 & 0x0f) << 2; $c2 = ord($input[$i++]); $c1 |= $c2 >> 6; $output .= $itoa64[$c1]; $output .= $itoa64[$c2 & 0x3f]; } while (1); return $output; } function HashPassword($password) { $random = ''; if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) { $random = $this->get_random_bytes(16); $hash = crypt($password, $this->gensalt_blowfish($random)); if (strlen($hash) == 60) return $hash; } if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) { if (strlen($random) < 3) $random = $this->get_random_bytes(3); $hash = crypt($password, $this->gensalt_extended($random)); if (strlen($hash) == 20) return $hash; } if (strlen($random) < 6) $random = $this->get_random_bytes(6); $hash = $this->crypt_private($password, $this->gensalt_private($random)); if (strlen($hash) == 34) return $hash; # Returning '*' on error is safe here, but would _not_ be safe # in a crypt(3)-like function used _both_ for generating new # hashes and for validating passwords against existing hashes. return '*'; } function CheckPassword($password, $stored_hash) { $hash = $this->crypt_private($password, $stored_hash); if ($hash[0] == '*') $hash = crypt($password, $stored_hash); return $hash == $stored_hash; } } ?>
0x6a
trunk/application/libraries/phpass-0.1/PasswordHash.php
PHP
asf20
6,598
<?php /* * This is a PHP library that handles calling reCAPTCHA. * - Documentation and latest version * http://recaptcha.net/plugins/php/ * - Get a reCAPTCHA API Key * https://www.google.com/recaptcha/admin/create * - Discussion group * http://groups.google.com/group/recaptcha * * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net * AUTHORS: * Mike Crawford * Ben Maurer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * The reCAPTCHA server URL's */ define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api"); define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api"); define("RECAPTCHA_VERIFY_SERVER", "www.google.com"); /** * Encodes the given data into a query string format * @param $data - array of string elements to be encoded * @return string - encoded request */ function _recaptcha_qsencode ($data) { $req = ""; foreach ( $data as $key => $value ) $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; // Cut the last '&' $req=substr($req,0,strlen($req)-1); return $req; } /** * Submits an HTTP POST to a reCAPTCHA server * @param string $host * @param string $path * @param array $data * @param int port * @return array response */ function _recaptcha_http_post($host, $path, $data, $port = 80) { $req = _recaptcha_qsencode ($data); $http_request = "POST $path HTTP/1.0\r\n"; $http_request .= "Host: $host\r\n"; $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $http_request .= "Content-Length: " . strlen($req) . "\r\n"; $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; $http_request .= "\r\n"; $http_request .= $req; $response = ''; if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { die ('Could not open socket'); } fwrite($fs, $http_request); while ( !feof($fs) ) $response .= fgets($fs, 1160); // One TCP-IP packet fclose($fs); $response = explode("\r\n\r\n", $response, 2); return $response; } /** * Gets the challenge HTML (javascript and non-javascript version). * This is called from the browser, and the resulting reCAPTCHA HTML widget * is embedded within the HTML form it was called from. * @param string $pubkey A public key for reCAPTCHA * @param string $error The error given by reCAPTCHA (optional, default is null) * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false) * @return string - The HTML to be embedded in the user's form. */ function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) { if ($pubkey == null || $pubkey == '') { die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ($use_ssl) { $server = RECAPTCHA_API_SECURE_SERVER; } else { $server = RECAPTCHA_API_SERVER; } $errorpart = ""; if ($error) { $errorpart = "&amp;error=" . $error; } return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script> <noscript> <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/> </noscript>'; } /** * A ReCaptchaResponse is returned from recaptcha_check_answer() */ class ReCaptchaResponse { var $is_valid; var $error; } /** * Calls an HTTP POST function to verify if the user's guess was correct * @param string $privkey * @param string $remoteip * @param string $challenge * @param string $response * @param array $extra_params an array of extra variables to post to the server * @return ReCaptchaResponse */ function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()) { if ($privkey == null || $privkey == '') { die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ($remoteip == null || $remoteip == '') { die ("For security reasons, you must pass the remote ip to reCAPTCHA"); } //discard spam submissions if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { $recaptcha_response = new ReCaptchaResponse(); $recaptcha_response->is_valid = false; $recaptcha_response->error = 'incorrect-captcha-sol'; return $recaptcha_response; } $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify", array ( 'privatekey' => $privkey, 'remoteip' => $remoteip, 'challenge' => $challenge, 'response' => $response ) + $extra_params ); $answers = explode ("\n", $response [1]); $recaptcha_response = new ReCaptchaResponse(); if (trim ($answers [0]) == 'true') { $recaptcha_response->is_valid = true; } else { $recaptcha_response->is_valid = false; $recaptcha_response->error = $answers [1]; } return $recaptcha_response; } /** * gets a URL where the user can sign up for reCAPTCHA. If your application * has a configuration page where you enter a key, you should provide a link * using this function. * @param string $domain The domain where the page is hosted * @param string $appname The name of your application */ function recaptcha_get_signup_url ($domain = null, $appname = null) { return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname)); } function _recaptcha_aes_pad($val) { $block_size = 16; $numpad = $block_size - (strlen ($val) % $block_size); return str_pad($val, strlen ($val) + $numpad, chr($numpad)); } /* Mailhide related code */ function _recaptcha_aes_encrypt($val,$ky) { if (! function_exists ("mcrypt_encrypt")) { die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); } $mode=MCRYPT_MODE_CBC; $enc=MCRYPT_RIJNDAEL_128; $val=_recaptcha_aes_pad($val); return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); } function _recaptcha_mailhide_urlbase64 ($x) { return strtr(base64_encode ($x), '+/', '-_'); } /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ function recaptcha_mailhide_url($pubkey, $privkey, $email) { if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>"); } $ky = pack('H*', $privkey); $cryptmail = _recaptcha_aes_encrypt ($email, $ky); return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail); } /** * gets the parts of the email to expose to the user. * eg, given johndoe@example,com return ["john", "example.com"]. * the email is then displayed as john...@example.com */ function _recaptcha_mailhide_email_parts ($email) { $arr = preg_split("/@/", $email ); if (strlen ($arr[0]) <= 4) { $arr[0] = substr ($arr[0], 0, 1); } else if (strlen ($arr[0]) <= 6) { $arr[0] = substr ($arr[0], 0, 3); } else { $arr[0] = substr ($arr[0], 0, 4); } return $arr; } /** * Gets html to display an email address given a public an private key. * to get a key, go to: * * http://www.google.com/recaptcha/mailhide/apikey */ function recaptcha_mailhide_html($pubkey, $privkey, $email) { $emailparts = _recaptcha_mailhide_email_parts ($email); $url = recaptcha_mailhide_url ($pubkey, $privkey, $email); return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) . "' onclick=\"window.open('" . htmlentities ($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities ($emailparts [1]); } ?>
0x6a
trunk/application/libraries/recaptchalib.php
PHP
asf20
9,910
<?php # # This is a test program for the portable PHP password hashing framework. # # Written by Solar Designer and placed in the public domain. # See PasswordHash.php for more information. # require 'PasswordHash.php'; header('Content-type: text/plain'); $ok = 0; # Try to use stronger but system-specific hashes, with a possible fallback to # the weaker portable hashes. $t_hasher = new PasswordHash(8, FALSE); $correct = 'test12345'; $hash = $t_hasher->HashPassword($correct); print 'Hash: ' . $hash . "\n"; $check = $t_hasher->CheckPassword($correct, $hash); if ($check) $ok++; print "Check correct: '" . $check . "' (should be '1')\n"; $wrong = 'test12346'; $check = $t_hasher->CheckPassword($wrong, $hash); if (!$check) $ok++; print "Check wrong: '" . $check . "' (should be '0' or '')\n"; unset($t_hasher); # Force the use of weaker portable hashes. $t_hasher = new PasswordHash(8, TRUE); $hash = $t_hasher->HashPassword($correct); print 'Hash: ' . $hash . "\n"; $check = $t_hasher->CheckPassword($correct, $hash); if ($check) $ok++; print "Check correct: '" . $check . "' (should be '1')\n"; $check = $t_hasher->CheckPassword($wrong, $hash); if (!$check) $ok++; print "Check wrong: '" . $check . "' (should be '0' or '')\n"; # A correct portable hash for 'test12345'. # Please note the use of single quotes to ensure that the dollar signs will # be interpreted literally. Of course, a real application making use of the # framework won't store password hashes within a PHP source file anyway. # We only do this for testing. $hash = '$P$9IQRaTwmfeRo7ud9Fh4E2PdI0S3r.L0'; print 'Hash: ' . $hash . "\n"; $check = $t_hasher->CheckPassword($correct, $hash); if ($check) $ok++; print "Check correct: '" . $check . "' (should be '1')\n"; $check = $t_hasher->CheckPassword($wrong, $hash); if (!$check) $ok++; print "Check wrong: '" . $check . "' (should be '0' or '')\n"; if ($ok == 6) print "All tests have PASSED\n"; else print "Some tests have FAILED\n"; ?>
0x6a
trunk/application/libraries/phpass/test.php
PHP
asf20
1,984
# # Written by Solar Designer and placed in the public domain. # See crypt_private.c for more information. # CC = gcc LD = $(CC) RM = rm -f CFLAGS = -Wall -O2 -fomit-frame-pointer -funroll-loops LDFLAGS = -s LIBS = -lcrypto all: crypt_private-test crypt_private-test: crypt_private-test.o $(LD) $(LDFLAGS) $(LIBS) crypt_private-test.o -o $@ crypt_private-test.o: crypt_private.c $(CC) -c $(CFLAGS) crypt_private.c -DTEST -o $@ clean: $(RM) crypt_private-test*
0x6a
trunk/application/libraries/phpass/c/Makefile
Makefile
asf20
467
/* * This code exists for the sole purpose to serve as another implementation * of the "private" password hashing method implemened in PasswordHash.php * and thus to confirm that these password hashes are indeed calculated as * intended. * * Other uses of this code are discouraged. There are much better password * hashing algorithms available to C programmers; one of those is bcrypt: * * http://www.openwall.com/crypt/ * * Written by Solar Designer <solar at openwall.com> in 2005 and placed in * the public domain. * * There's absolutely no warranty. */ #include <string.h> #include <openssl/md5.h> #ifdef TEST #include <stdio.h> #endif static char *itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static void encode64(char *dst, char *src, int count) { int i, value; i = 0; do { value = (unsigned char)src[i++]; *dst++ = itoa64[value & 0x3f]; if (i < count) value |= (unsigned char)src[i] << 8; *dst++ = itoa64[(value >> 6) & 0x3f]; if (i++ >= count) break; if (i < count) value |= (unsigned char)src[i] << 16; *dst++ = itoa64[(value >> 12) & 0x3f]; if (i++ >= count) break; *dst++ = itoa64[(value >> 18) & 0x3f]; } while (i < count); } char *crypt_private(char *password, char *setting) { static char output[35]; MD5_CTX ctx; char hash[MD5_DIGEST_LENGTH]; char *p, *salt; int count_log2, length, count; strcpy(output, "*0"); if (!strncmp(setting, output, 2)) output[1] = '1'; if (strncmp(setting, "$P$", 3)) return output; p = strchr(itoa64, setting[3]); if (!p) return output; count_log2 = p - itoa64; if (count_log2 < 7 || count_log2 > 30) return output; salt = setting + 4; if (strlen(salt) < 8) return output; length = strlen(password); MD5_Init(&ctx); MD5_Update(&ctx, salt, 8); MD5_Update(&ctx, password, length); MD5_Final(hash, &ctx); count = 1 << count_log2; do { MD5_Init(&ctx); MD5_Update(&ctx, hash, MD5_DIGEST_LENGTH); MD5_Update(&ctx, password, length); MD5_Final(hash, &ctx); } while (--count); memcpy(output, setting, 12); encode64(&output[12], hash, MD5_DIGEST_LENGTH); return output; } #ifdef TEST int main(int argc, char **argv) { if (argc != 3) return 1; puts(crypt_private(argv[1], argv[2])); return 0; } #endif
0x6a
trunk/application/libraries/phpass/c/crypt_private.c
C
asf20
2,283
<?php # # Portable PHP password hashing framework. # # Version 0.3 / genuine. # # Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in # the public domain. Revised in subsequent years, still public domain. # # There's absolutely no warranty. # # The homepage URL for this framework is: # # http://www.openwall.com/phpass/ # # Please be sure to update the Version line if you edit this file in any way. # It is suggested that you leave the main version number intact, but indicate # your project name (after the slash) and add your own revision information. # # Please do not change the "private" password hashing method implemented in # here, thereby making your hashes incompatible. However, if you must, please # change the hash type identifier (the "$P$") to something different. # # Obviously, since this code is in the public domain, the above are not # requirements (there can be none), but merely suggestions. # class PasswordHash { var $itoa64; var $iteration_count_log2; var $portable_hashes; var $random_state; function PasswordHash($iteration_count_log2, $portable_hashes) { $this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) $iteration_count_log2 = 8; $this->iteration_count_log2 = $iteration_count_log2; $this->portable_hashes = $portable_hashes; $this->random_state = microtime(); if (function_exists('getmypid')) $this->random_state .= getmypid(); } function get_random_bytes($count) { $output = ''; if (is_readable('/dev/urandom') && ($fh = @fopen('/dev/urandom', 'rb'))) { $output = fread($fh, $count); fclose($fh); } if (strlen($output) < $count) { $output = ''; for ($i = 0; $i < $count; $i += 16) { $this->random_state = md5(microtime() . $this->random_state); $output .= pack('H*', md5($this->random_state)); } $output = substr($output, 0, $count); } return $output; } function encode64($input, $count) { $output = ''; $i = 0; do { $value = ord($input[$i++]); $output .= $this->itoa64[$value & 0x3f]; if ($i < $count) $value |= ord($input[$i]) << 8; $output .= $this->itoa64[($value >> 6) & 0x3f]; if ($i++ >= $count) break; if ($i < $count) $value |= ord($input[$i]) << 16; $output .= $this->itoa64[($value >> 12) & 0x3f]; if ($i++ >= $count) break; $output .= $this->itoa64[($value >> 18) & 0x3f]; } while ($i < $count); return $output; } function gensalt_private($input) { $output = '$P$'; $output .= $this->itoa64[min($this->iteration_count_log2 + ((PHP_VERSION >= '5') ? 5 : 3), 30)]; $output .= $this->encode64($input, 6); return $output; } function crypt_private($password, $setting) { $output = '*0'; if (substr($setting, 0, 2) == $output) $output = '*1'; $id = substr($setting, 0, 3); # We use "$P$", phpBB3 uses "$H$" for the same thing if ($id != '$P$' && $id != '$H$') return $output; $count_log2 = strpos($this->itoa64, $setting[3]); if ($count_log2 < 7 || $count_log2 > 30) return $output; $count = 1 << $count_log2; $salt = substr($setting, 4, 8); if (strlen($salt) != 8) return $output; # We're kind of forced to use MD5 here since it's the only # cryptographic primitive available in all versions of PHP # currently in use. To implement our own low-level crypto # in PHP would result in much worse performance and # consequently in lower iteration counts and hashes that are # quicker to crack (by non-PHP code). if (PHP_VERSION >= '5') { $hash = md5($salt . $password, TRUE); do { $hash = md5($hash . $password, TRUE); } while (--$count); } else { $hash = pack('H*', md5($salt . $password)); do { $hash = pack('H*', md5($hash . $password)); } while (--$count); } $output = substr($setting, 0, 12); $output .= $this->encode64($hash, 16); return $output; } function gensalt_extended($input) { $count_log2 = min($this->iteration_count_log2 + 8, 24); # This should be odd to not reveal weak DES keys, and the # maximum valid value is (2**24 - 1) which is odd anyway. $count = (1 << $count_log2) - 1; $output = '_'; $output .= $this->itoa64[$count & 0x3f]; $output .= $this->itoa64[($count >> 6) & 0x3f]; $output .= $this->itoa64[($count >> 12) & 0x3f]; $output .= $this->itoa64[($count >> 18) & 0x3f]; $output .= $this->encode64($input, 3); return $output; } function gensalt_blowfish($input) { # This one needs to use a different order of characters and a # different encoding scheme from the one in encode64() above. # We care because the last character in our encoded string will # only represent 2 bits. While two known implementations of # bcrypt will happily accept and correct a salt string which # has the 4 unused bits set to non-zero, we do not want to take # chances and we also do not want to waste an additional byte # of entropy. $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $output = '$2a$'; $output .= chr(ord('0') + $this->iteration_count_log2 / 10); $output .= chr(ord('0') + $this->iteration_count_log2 % 10); $output .= '$'; $i = 0; do { $c1 = ord($input[$i++]); $output .= $itoa64[$c1 >> 2]; $c1 = ($c1 & 0x03) << 4; if ($i >= 16) { $output .= $itoa64[$c1]; break; } $c2 = ord($input[$i++]); $c1 |= $c2 >> 4; $output .= $itoa64[$c1]; $c1 = ($c2 & 0x0f) << 2; $c2 = ord($input[$i++]); $c1 |= $c2 >> 6; $output .= $itoa64[$c1]; $output .= $itoa64[$c2 & 0x3f]; } while (1); return $output; } function HashPassword($password) { $random = ''; if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) { $random = $this->get_random_bytes(16); $hash = crypt($password, $this->gensalt_blowfish($random)); if (strlen($hash) == 60) return $hash; } if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) { if (strlen($random) < 3) $random = $this->get_random_bytes(3); $hash = crypt($password, $this->gensalt_extended($random)); if (strlen($hash) == 20) return $hash; } if (strlen($random) < 6) $random = $this->get_random_bytes(6); $hash = $this->crypt_private($password, $this->gensalt_private($random)); if (strlen($hash) == 34) return $hash; # Returning '*' on error is safe here, but would _not_ be safe # in a crypt(3)-like function used _both_ for generating new # hashes and for validating passwords against existing hashes. return '*'; } function CheckPassword($password, $stored_hash) { $hash = $this->crypt_private($password, $stored_hash); if ($hash[0] == '*') $hash = crypt($password, $stored_hash); return $hash == $stored_hash; } } ?>
0x6a
trunk/application/libraries/phpass/PasswordHash.php
PHP
asf20
6,830
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); require_once("smarty3/Smarty.class.php"); class CI_Smarty3 extends Smarty { var $lang = ''; function __construct() { parent::__construct(); //$this->template_dir = APPPATH."views/"; $this->compile_dir = 'views'; $this->caching = 0; //0 = no caching; 1 = use class cache_lifetime value; 2 = use cache_lifetime in cache file $this->cache_dir = 'cache'; $this->cache_lifetime = 3600; $this->left_delimiter = '{{'; $this->right_delimiter = '}}'; //$this->debugging = TRUE; //global $URI; //if(!empty($URI->segments[1])){ //$this->lang = $URI->segments[1].'/'; //} } function display($html){ if(substr_count($html,".")==0){ $filePath = APPPATH."views/$html.tpl"; }else{ $filePath = APPPATH."views/$html"; } if(file_exists($filePath)){ parent::display($filePath); }else{ show_error('Unable to load the requested file: '.$filePath); } } function view($name,$location='pagecontent',$get=false){ if(substr_count($name,".")==0){ $filePath = APPPATH."".$name.'.tpl'; }else{ $filePath = APPPATH."views/".$name; } //echo $filePath; if(file_exists($filePath)){ $content = $this->fetch($filePath); $this->assign($location,$content); if($get){ return $content; } }else{ show_error('Unable to load the requested file: '.$filePath); } } function get_contents($html){ if(substr_count($html,".")==0){ $filePath = APPPATH."views/".$html.'.tpl'; }else{ $filePath = APPPATH."views/".$html; } if(file_exists($filePath)){ return $this->fetch($filePath); }else{ show_error('Unable to load the requested file: '.$filePath); } } } ?>
0x6a
trunk/application/libraries/smarty3.php
PHP
asf20
1,879
<?php /** * Smarty plugin * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty lower modifier plugin * * Type: modifier<br> * Name: lower<br> * Purpose: convert string to lowercase * * @link http://www.smarty.net/manual/en/language.modifier.lower.php lower (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_lower($params, $compiler) { if (Smarty::$_MBSTRING) { return 'mb_strtolower(' . $params[0] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')' ; } // no MBString fallback return 'strtolower(' . $params[0] . ')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.lower.php
PHP
asf20
764
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifier */ /** * Smarty capitalize modifier plugin * * Type: modifier<br> * Name: capitalize<br> * Purpose: capitalize words in the string * * {@internal {$string|capitalize:true:true} is the fastest option for MBString enabled systems }} * * @param string $string string to capitalize * @param boolean $uc_digits also capitalize "x123" to "X123" * @param boolean $lc_rest capitalize first letters, lowercase all following letters "aAa" to "Aaa" * @return string capitalized string * @author Monte Ohrt <monte at ohrt dot com> * @author Rodney Rehm */ function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = false) { if (Smarty::$_MBSTRING) { if ($lc_rest) { // uppercase (including hyphenated words) $upper_string = mb_convert_case( $string, MB_CASE_TITLE, Smarty::$_CHARSET ); } else { // uppercase word breaks $upper_string = preg_replace("!(^|[^\p{L}'])([\p{Ll}])!eS" . Smarty::$_UTF8_MODIFIER, "stripslashes('\\1').mb_convert_case(stripslashes('\\2'),MB_CASE_UPPER, '" . addslashes(Smarty::$_CHARSET) . "')", $string); } // check uc_digits case if (!$uc_digits) { if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches, PREG_OFFSET_CAPTURE)) { foreach($matches[1] as $match) { $upper_string = substr_replace($upper_string, mb_strtolower($match[0], Smarty::$_CHARSET), $match[1], strlen($match[0])); } } } $upper_string = preg_replace("!((^|\s)['\"])(\w)!e" . Smarty::$_UTF8_MODIFIER, "stripslashes('\\1').mb_convert_case(stripslashes('\\3'),MB_CASE_UPPER, '" . addslashes(Smarty::$_CHARSET) . "')", $upper_string); return $upper_string; } // lowercase first if ($lc_rest) { $string = strtolower($string); } // uppercase (including hyphenated words) $upper_string = preg_replace("!(^|[^\p{L}'])([\p{Ll}])!eS" . Smarty::$_UTF8_MODIFIER, "stripslashes('\\1').ucfirst(stripslashes('\\2'))", $string); // check uc_digits case if (!$uc_digits) { if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches, PREG_OFFSET_CAPTURE)) { foreach($matches[1] as $match) { $upper_string = substr_replace($upper_string, strtolower($match[0]), $match[1], strlen($match[0])); } } } $upper_string = preg_replace("!((^|\s)['\"])(\w)!e" . Smarty::$_UTF8_MODIFIER, "stripslashes('\\1').strtoupper(stripslashes('\\3'))", $upper_string); return $upper_string; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifier.capitalize.php
PHP
asf20
2,829
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty count_sentences modifier plugin * * Type: modifier<br> * Name: count_sentences * Purpose: count the number of sentences in a text * * @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php * count_sentences (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_count_sentences($params, $compiler) { // find periods, question marks, exclamation marks with a word before but not after. return 'preg_match_all("#\w[\.\?\!](\W|$)#S' . Smarty::$_UTF8_MODIFIER . '", ' . $params[0] . ', $tmp)'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.count_sentences.php
PHP
asf20
781
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifier */ /** * 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://www.smarty.net/manual/en/language.modifier.date.format.php date_format (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string $string input date string * @param string $format strftime format for output * @param string $default_date default date if $string is empty * @param string $formatter either 'strftime' or 'auto' * @return string |void * @uses smarty_make_timestamp() */ function smarty_modifier_date_format($string, $format=null, $default_date='', $formatter='auto') { date_default_timezone_set('Asia/Ho_Chi_Minh'); if ($format === null) { $format = Smarty::$_DATE_FORMAT; } /** * Include the {@link shared.make_timestamp.php} plugin */ require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'); if ($string != '') { $timestamp = smarty_make_timestamp($string); } elseif ($default_date != '') { $timestamp = smarty_make_timestamp($default_date); } else { return; } if($formatter=='strftime'||($formatter=='auto'&&strpos($format,'%')!==false)) { if (DS == '\\') { $_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); } else { return date($format, $timestamp); } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifier.date_format.php
PHP
asf20
2,311
<?php /** * Smarty plugin to format text blocks * * @package Smarty * @subpackage PluginsBlock */ /** * 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> * Params: * <pre> * - style - string (email) * - indent - integer (0) * - wrap - integer (80) * - wrap_char - string ("\n") * - indent_char - string (" ") * - wrap_boundary - boolean (true) * </pre> * * @link http://www.smarty.net/manual/en/language.function.textformat.php {textformat} * (Smarty online manual) * @param array $params parameters * @param string $content contents of the block * @param Smarty_Internal_Template $template template object * @param boolean &$repeat repeat flag * @return string content re-formatted * @author Monte Ohrt <monte at ohrt dot com> */ function smarty_block_textformat($params, $content, $template, &$repeat) { 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: trigger_error("textformat: unknown attribute '$_key'"); } } if ($style == 'email') { $wrap = 72; } // split into paragraphs $_paragraphs = preg_split('![\r\n]{2}!', $content); $_output = ''; foreach ($_paragraphs as &$_paragraph) { if (!$_paragraph) { continue; } // convert mult. spaces & special chars to single space $_paragraph = preg_replace(array('!\s+!' . Smarty::$_UTF8_MODIFIER, '!(^\s+)|(\s+$)!' . Smarty::$_UTF8_MODIFIER), array(' ', ''), $_paragraph); // indent first line if ($indent_first > 0) { $_paragraph = str_repeat($indent_char, $indent_first) . $_paragraph; } // wordwrap sentences if (Smarty::$_MBSTRING) { require_once(SMARTY_PLUGINS_DIR . 'shared.mb_wordwrap.php'); $_paragraph = smarty_mb_wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut); } else { $_paragraph = wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut); } // indent lines if ($indent > 0) { $_paragraph = preg_replace('!^!m', str_repeat($indent_char, $indent), $_paragraph); } } $_output = implode($wrap_char . $wrap_char, $_paragraphs); if ($assign) { $template->assign($assign, $_output); } else { return $_output; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/block.textformat.php
PHP
asf20
3,346
<?php /** * Smarty plugin * @package Smarty * @subpackage PluginsFunction */ /** * 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://www.smarty.net/manual/en/language.function.counter.php {counter} * (Smarty online manual) * @param array $params parameters * @param Smarty_Internal_Template $template template object * @return string|null */ function smarty_function_counter($params, $template) { 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'])) { $template->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; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.counter.php
PHP
asf20
1,907
<?php /** * Smarty shared plugin * * @package Smarty * @subpackage PluginsShared */ /** * 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 DateTime|int|string $string date object, timestamp or string that can be converted using strtotime() * @return int */ function smarty_make_timestamp($string) { if (empty($string)) { // use "now": return time(); } elseif ($string instanceof DateTime) { return $string->getTimestamp(); } elseif (strlen($string) == 14 && ctype_digit($string)) { // it is mysql timestamp format of YYYYMMDDHHMMSS? return 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 return (int) $string; } else { // strtotime should handle it $time = strtotime($string); if ($time == -1 || $time === false) { // strtotime() was not able to parse $string, use "now": return time(); } return $time; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/shared.make_timestamp.php
PHP
asf20
1,339
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * 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 Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_wordwrap($params, $compiler) { if (!isset($params[1])) { $params[1] = 80; } if (!isset($params[2])) { $params[2] = '"\n"'; } if (!isset($params[3])) { $params[3] = 'false'; } $function = 'wordwrap'; if (Smarty::$_MBSTRING) { if ($compiler->tag_nocache | $compiler->nocache) { $compiler->template->required_plugins['nocache']['wordwrap']['modifier']['file'] = SMARTY_PLUGINS_DIR .'shared.mb_wordwrap.php'; $compiler->template->required_plugins['nocache']['wordwrap']['modifier']['function'] = 'smarty_mb_wordwrap'; } else { $compiler->template->required_plugins['compiled']['wordwrap']['modifier']['file'] = SMARTY_PLUGINS_DIR .'shared.mb_wordwrap.php'; $compiler->template->required_plugins['compiled']['wordwrap']['modifier']['function'] = 'smarty_mb_wordwrap'; } $function = 'smarty_mb_wordwrap'; } return $function . '(' . $params[0] . ',' . $params[1] . ',' . $params[2] . ',' . $params[3] . ')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.wordwrap.php
PHP
asf20
1,578
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * @ignore */ require_once( SMARTY_PLUGINS_DIR .'shared.literal_compiler_param.php' ); /** * Smarty escape modifier plugin * * Type: modifier<br> * Name: escape<br> * Purpose: escape string for output * * @link http://www.smarty.net/docsv2/en/language.modifier.escape count_characters (Smarty online manual) * @author Rodney Rehm * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_escape($params, $compiler) { try { $esc_type = smarty_literal_compiler_param($params, 1, 'html'); $char_set = smarty_literal_compiler_param($params, 2, Smarty::$_CHARSET); $double_encode = smarty_literal_compiler_param($params, 3, true); if (!$char_set) { $char_set = Smarty::$_CHARSET; } switch ($esc_type) { case 'html': return 'htmlspecialchars(' . $params[0] .', ENT_QUOTES, ' . var_export($char_set, true) . ', ' . var_export($double_encode, true) . ')'; case 'htmlall': if (Smarty::$_MBSTRING) { return 'mb_convert_encoding(htmlspecialchars(' . $params[0] .', ENT_QUOTES, ' . var_export($char_set, true) . ', ' . var_export($double_encode, true) . '), "HTML-ENTITIES", ' . var_export($char_set, true) . ')'; } // no MBString fallback return 'htmlentities(' . $params[0] .', ENT_QUOTES, ' . var_export($char_set, true) . ', ' . var_export($double_encode, true) . ')'; case 'url': return 'rawurlencode(' . $params[0] . ')'; case 'urlpathinfo': return 'str_replace("%2F", "/", rawurlencode(' . $params[0] . '))'; case 'quotes': // escape unescaped single quotes return 'preg_replace("%(?<!\\\\\\\\)\'%", "\\\'",' . $params[0] . ')'; case 'javascript': // escape quotes and backslashes, newlines, etc. return 'strtr(' . $params[0] . ', array("\\\\" => "\\\\\\\\", "\'" => "\\\\\'", "\"" => "\\\\\"", "\\r" => "\\\\r", "\\n" => "\\\n", "</" => "<\/" ))'; } } catch(SmartyException $e) { // pass through to regular plugin fallback } // could not optimize |escape call, so fallback to regular plugin if ($compiler->tag_nocache | $compiler->nocache) { $compiler->template->required_plugins['nocache']['escape']['modifier']['file'] = SMARTY_PLUGINS_DIR .'modifier.escape.php'; $compiler->template->required_plugins['nocache']['escape']['modifier']['function'] = 'smarty_modifier_escape'; } else { $compiler->template->required_plugins['compiled']['escape']['modifier']['file'] = SMARTY_PLUGINS_DIR .'modifier.escape.php'; $compiler->template->required_plugins['compiled']['escape']['modifier']['function'] = 'smarty_modifier_escape'; } return 'smarty_modifier_escape(' . join( ', ', $params ) . ')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.escape.php
PHP
asf20
3,404
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsShared */ /** * evaluate compiler parameter * * @param array $params parameter array as given to the compiler function * @param integer $index array index of the parameter to convert * @param mixed $default value to be returned if the parameter is not present * @return mixed evaluated value of parameter or $default * @throws SmartyException if parameter is not a literal (but an expression, variable, …) * @author Rodney Rehm */ function smarty_literal_compiler_param($params, $index, $default=null) { // not set, go default if (!isset($params[$index])) { return $default; } // test if param is a literal if (!preg_match('/^([\'"]?)[a-zA-Z0-9]+(\\1)$/', $params[$index])) { throw new SmartyException('$param[' . $index . '] is not a literal and is thus not evaluatable at compile time'); } $t = null; eval("\$t = " . $params[$index] . ";"); return $t; }
0x6a
trunk/application/libraries/smarty3/plugins/shared.literal_compiler_param.php
PHP
asf20
1,033
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * 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;"}<br> * Date: September 25th, 2002 * * @link http://www.smarty.net/manual/en/language.modifier.strip.php strip (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_strip($params, $compiler) { if (!isset($params[1])) { $params[1] = "' '"; } return "preg_replace('!\s+!" . Smarty::$_UTF8_MODIFIER . "', {$params[1]},{$params[0]})"; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.strip.php
PHP
asf20
850
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty strip_tags modifier plugin * * Type: modifier<br> * Name: strip_tags<br> * Purpose: strip html tags from text * * @link http://www.smarty.net/manual/en/language.modifier.strip.tags.php strip_tags (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_strip_tags($params, $compiler) { if (!isset($params[1])) { $params[1] = true; } if ($params[1] === true) { return "preg_replace('!<[^>]*?>!', ' ', {$params[0]})"; } else { return 'strip_tags(' . $params[0] . ')'; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.strip_tags.php
PHP
asf20
765
<?php /** * Smarty plugin * * This plugin is only for Smarty2 BC * @package Smarty * @subpackage PluginsFunction */ /** * Smarty {math} function plugin * * Type: function<br> * Name: math<br> * Purpose: handle math computations in template * * @link http://www.smarty.net/manual/en/language.function.math.php {math} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array $params parameters * @param Smarty_Internal_Template $template template object * @return string|null */ function smarty_function_math($params, $template) { static $_allowed_funcs = array( 'int' => true, 'abs' => true, 'ceil' => true, 'cos' => true, 'exp' => true, 'floor' => true, 'log' => true, 'log10' => true, 'max' => true, 'min' => true, 'pi' => true, 'pow' => true, 'rand' => true, 'round' => true, 'sin' => true, 'sqrt' => true, 'srand' => true ,'tan' => true ); // be sure equation parameter is present if (empty($params['equation'])) { trigger_error("math: missing equation parameter",E_USER_WARNING); return; } $equation = $params['equation']; // make sure parenthesis are balanced if (substr_count($equation,"(") != substr_count($equation,")")) { trigger_error("math: unbalanced parenthesis",E_USER_WARNING); return; } // match all vars in equation, make sure all are passed preg_match_all("!(?:0x[a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9_]*)!",$equation, $match); foreach($match[1] as $curr_var) { if ($curr_var && !isset($params[$curr_var]) && !isset($_allowed_funcs[$curr_var])) { trigger_error("math: function call $curr_var not allowed",E_USER_WARNING); return; } } foreach($params as $key => $val) { if ($key != "equation" && $key != "format" && $key != "assign") { // make sure value is not empty if (strlen($val)==0) { trigger_error("math: parameter $key is empty",E_USER_WARNING); return; } if (!is_numeric($val)) { trigger_error("math: parameter $key: is not numeric",E_USER_WARNING); return; } $equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation); } } $smarty_math_result = null; eval("\$smarty_math_result = ".$equation.";"); if (empty($params['format'])) { if (empty($params['assign'])) { return $smarty_math_result; } else { $template->assign($params['assign'],$smarty_math_result); } } else { if (empty($params['assign'])){ printf($params['format'],$smarty_math_result); } else { $template->assign($params['assign'],sprintf($params['format'],$smarty_math_result)); } } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.math.php
PHP
asf20
2,989
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * Smarty {html_options} function plugin * * Type: function<br> * Name: html_options<br> * Purpose: Prints the list of <option> tags generated from * the passed parameters<br> * Params: * <pre> * - 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 * - id (optional) - string default not set * - class (optional) - string default not set * </pre> * * @link http://www.smarty.net/manual/en/language.function.html.options.php {html_image} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @author Ralf Strehle (minor optimization) <ralf dot strehle at yahoo dot de> * @param array $params parameters * @param Smarty_Internal_Template $template template object * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_options($params, $template) { require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'); $name = null; $values = null; $options = null; $selected = null; $output = null; $id = null; $class = null; $extra = ''; foreach ($params as $_key => $_val) { switch ($_key) { case 'name': case 'class': case 'id': $$_key = (string) $_val; break; case 'options': $options = (array) $_val; break; case 'values': case 'output': $$_key = array_values((array) $_val); break; case 'selected': if (is_array($_val)) { $selected = array(); foreach ($_val as $_sel) { if (is_object($_sel)) { if (method_exists($_sel, "__toString")) { $_sel = smarty_function_escape_special_chars((string) $_sel->__toString()); } else { trigger_error("html_options: selected attribute contains an object of class '". get_class($_sel) ."' without __toString() method", E_USER_NOTICE); continue; } } else { $_sel = smarty_function_escape_special_chars((string) $_sel); } $selected[$_sel] = true; } } elseif (is_object($_val)) { if (method_exists($_val, "__toString")) { $selected = smarty_function_escape_special_chars((string) $_val->__toString()); } else { trigger_error("html_options: selected attribute is an object of class '". get_class($_val) ."' without __toString() method", E_USER_NOTICE); } } else { $selected = smarty_function_escape_special_chars((string) $_val); } break; default: if (!is_array($_val)) { $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"'; } else { trigger_error("html_options: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (!isset($options) && !isset($values)) { /* raise error here? */ return ''; } $_html_result = ''; $_idx = 0; if (isset($options)) { foreach ($options as $_key => $_val) { $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $_idx); } } else { foreach ($values as $_i => $_key) { $_val = isset($output[$_i]) ? $output[$_i] : ''; $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $_idx); } } if (!empty($name)) { $_html_class = !empty($class) ? ' class="'.$class.'"' : ''; $_html_id = !empty($id) ? ' id="'.$id.'"' : ''; $_html_result = '<select name="' . $name . '"' . $_html_class . $_html_id . $extra . '>' . "\n" . $_html_result . '</select>' . "\n"; } return $_html_result; } function smarty_function_html_options_optoutput($key, $value, $selected, $id, $class, &$idx) { if (!is_array($value)) { $_key = smarty_function_escape_special_chars($key); $_html_result = '<option value="' . $_key . '"'; if (is_array($selected)) { if (isset($selected[$_key])) { $_html_result .= ' selected="selected"'; } } elseif ($_key === $selected) { $_html_result .= ' selected="selected"'; } $_html_class = !empty($class) ? ' class="'.$class.' option"' : ''; $_html_id = !empty($id) ? ' id="'.$id.'-'.$idx.'"' : ''; if (is_object($value)) { if (method_exists($value, "__toString")) { $value = smarty_function_escape_special_chars((string) $value->__toString()); } else { trigger_error("html_options: value is an object of class '". get_class($value) ."' without __toString() method", E_USER_NOTICE); return ''; } } $_html_result .= $_html_class . $_html_id . '>' . $value . '</option>' . "\n"; $idx++; } else { $_idx = 0; $_html_result = smarty_function_html_options_optgroup($key, $value, $selected, !empty($id) ? ($id.'-'.$idx) : null, $class, $_idx); $idx++; } return $_html_result; } function smarty_function_html_options_optgroup($key, $values, $selected, $id, $class, &$idx) { $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, $id, $class, $idx); } $optgroup_html .= "</optgroup>\n"; return $optgroup_html; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.html_options.php
PHP
asf20
6,596
<?php /** * Smarty plugin * * @package Smarty * @subpackage Debug */ /** * Smarty debug_print_var modifier plugin * * Type: modifier<br> * Name: debug_print_var<br> * Purpose: formats variable contents for display in the console * * @author Monte Ohrt <monte at ohrt dot com> * @param array|object $var variable to be formatted * @param integer $depth maximum recursion depth if $var is an array * @param integer $length maximum string length if $var is a string * @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 (Smarty::$_MBSTRING) { if (mb_strlen($var, Smarty::$_CHARSET) > $length) { $results = mb_substr($var, 0, $length - 3, Smarty::$_CHARSET) . '...'; } } else { if (isset($var[$length])) { $results = substr($var, 0, $length - 3) . '...'; } } $results = htmlspecialchars('"' . $results . '"'); break; case 'unknown type' : default : $results = strtr((string) $var, $_replace); if (Smarty::$_MBSTRING) { if (mb_strlen($results, Smarty::$_CHARSET) > $length) { $results = mb_substr($results, 0, $length - 3, Smarty::$_CHARSET) . '...'; } } else { if (strlen($results) > $length) { $results = substr($results, 0, $length - 3) . '...'; } } $results = htmlspecialchars($results); } return $results; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifier.debug_print_var.php
PHP
asf20
3,572
<?php /** * Smarty plugin * @package Smarty * @subpackage PluginsModifier */ /** * 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 $string input string * @param string $spacify_char string to insert between characters. * @return string */ function smarty_modifier_spacify($string, $spacify_char = ' ') { // well… what about charsets besides latin and UTF-8? return implode($spacify_char, preg_split('//' . Smarty::$_UTF8_MODIFIER, $string, -1, PREG_SPLIT_NO_EMPTY)); } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifier.spacify.php
PHP
asf20
787
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifier */ /** * Smarty escape modifier plugin * * Type: modifier<br> * Name: escape<br> * Purpose: escape string for output * * @link http://www.smarty.net/manual/en/language.modifier.count.characters.php count_characters (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string $string input string * @param string $esc_type escape type * @param string $char_set character set, used for htmlspecialchars() or htmlentities() * @param boolean $double_encode encode already encoded entitites again, used for htmlspecialchars() or htmlentities() * @return string escaped input string */ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $double_encode = true) { if (!$char_set) { $char_set = Smarty::$_CHARSET; } switch ($esc_type) { case 'html': return htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode); case 'htmlall': if (Smarty::$_MBSTRING) { // mb_convert_encoding ignores htmlspecialchars() $string = htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode); // htmlentities() won't convert everything, so use mb_convert_encoding return mb_convert_encoding($string, 'HTML-ENTITIES', $char_set); } // no MBString fallback return htmlentities($string, ENT_QUOTES, $char_set, $double_encode); case 'url': return rawurlencode($string); case 'urlpathinfo': return str_replace('%2F', '/', rawurlencode($string)); case 'quotes': // escape unescaped single quotes return preg_replace("%(?<!\\\\)'%", "\\'", $string); case 'hex': // escape every byte into hex // Note that the UTF-8 encoded character ä will be represented as %c3%a4 $return = ''; $_length = strlen($string); for ($x = 0; $x < $_length; $x++) { $return .= '%' . bin2hex($string[$x]); } return $return; case 'hexentity': $return = ''; if (Smarty::$_MBSTRING) { require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php'); $return = ''; foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) { $return .= '&#x' . strtoupper(dechex($unicode)) . ';'; } return $return; } // no MBString fallback $_length = strlen($string); for ($x = 0; $x < $_length; $x++) { $return .= '&#x' . bin2hex($string[$x]) . ';'; } return $return; case 'decentity': $return = ''; if (Smarty::$_MBSTRING) { require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php'); $return = ''; foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) { $return .= '&#' . $unicode . ';'; } return $return; } // no MBString fallback $_length = strlen($string); for ($x = 0; $x < $_length; $x++) { $return .= '&#' . ord($string[$x]) . ';'; } return $return; case 'javascript': // escape quotes and backslashes, newlines, etc. return strtr($string, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"', "\r" => '\\r', "\n" => '\\n', '</' => '<\/')); case 'mail': if (Smarty::$_MBSTRING) { require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php'); return smarty_mb_str_replace(array('@', '.'), array(' [AT] ', ' [DOT] '), $string); } // no MBString fallback return str_replace(array('@', '.'), array(' [AT] ', ' [DOT] '), $string); case 'nonstd': // escape non-standard chars, such as ms document quotes $return = ''; if (Smarty::$_MBSTRING) { require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php'); foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) { if ($unicode >= 126) { $return .= '&#' . $unicode . ';'; } else { $return .= chr($unicode); } } return $return; } $_length = strlen($string); for ($_i = 0; $_i < $_length; $_i++) { $_ord = ord(substr($string, $_i, 1)); // non-standard char, escape it if ($_ord >= 126) { $return .= '&#' . $_ord . ';'; } else { $return .= substr($string, $_i, 1); } } return $return; default: return $string; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifier.escape.php
PHP
asf20
5,294
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty to_charset modifier plugin * * Type: modifier<br> * Name: to_charset<br> * Purpose: convert character encoding from internal encoding to $charset * * @author Rodney Rehm * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_to_charset($params, $compiler) { if (!Smarty::$_MBSTRING) { // FIXME: (rodneyrehm) shouldn't this throw an error? return $params[0]; } if (!isset($params[1])) { $params[1] = '"ISO-8859-1"'; } return 'mb_convert_encoding(' . $params[0] . ', ' . $params[1] . ', "' . addslashes(Smarty::$_CHARSET) . '")'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.to_charset.php
PHP
asf20
788
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty default modifier plugin * * Type: modifier<br> * Name: default<br> * Purpose: designate default value for empty variables * * @link http://www.smarty.net/manual/en/language.modifier.default.php default (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_default ($params, $compiler) { $output = $params[0]; if (!isset($params[1])) { $params[1] = "''"; } array_shift($params); foreach ($params as $param) { $output = '(($tmp = @' . $output . ')===null||$tmp===\'\' ? ' . $param . ' : $tmp)'; } return $output; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.default.php
PHP
asf20
819
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * 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> * 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> * Params: * <pre> * - 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 * - escape (optional) - escape the content (not value), defaults to true * </pre> * * @link http://www.smarty.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 $params parameters * @param object $template template object * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_checkboxes($params, $template) { require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'); $name = 'checkbox'; $values = null; $options = null; $selected = array(); $separator = ''; $escape = true; $labels = true; $label_ids = false; $output = null; $extra = ''; foreach($params as $_key => $_val) { switch($_key) { case 'name': case 'separator': $$_key = (string) $_val; break; case 'escape': 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 'checked': case 'selected': if (is_array($_val)) { $selected = array(); foreach ($_val as $_sel) { if (is_object($_sel)) { if (method_exists($_sel, "__toString")) { $_sel = smarty_function_escape_special_chars((string) $_sel->__toString()); } else { trigger_error("html_checkboxes: selected attribute contains an object of class '". get_class($_sel) ."' without __toString() method", E_USER_NOTICE); continue; } } else { $_sel = smarty_function_escape_special_chars((string) $_sel); } $selected[$_sel] = true; } } elseif (is_object($_val)) { if (method_exists($_val, "__toString")) { $selected = smarty_function_escape_special_chars((string) $_val->__toString()); } else { trigger_error("html_checkboxes: selected attribute is an object of class '". get_class($_val) ."' without __toString() method", E_USER_NOTICE); } } else { $selected = smarty_function_escape_special_chars((string) $_val); } break; case 'checkboxes': 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 { trigger_error("html_checkboxes: 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_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids, $escape); } } 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, $label_ids, $escape); } } if(!empty($params['assign'])) { $template->assign($params['assign'], $_html_result); } else { return implode("\n", $_html_result); } } function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids, $escape=true) { $_output = ''; if (is_object($value)) { if (method_exists($value, "__toString")) { $value = (string) $value->__toString(); } else { trigger_error("html_options: value is an object of class '". get_class($value) ."' without __toString() method", E_USER_NOTICE); return ''; } } else { $value = (string) $value; } if (is_object($output)) { if (method_exists($output, "__toString")) { $output = (string) $output->__toString(); } else { trigger_error("html_options: output is an object of class '". get_class($output) ."' without __toString() method", E_USER_NOTICE); return ''; } } else { $output = (string) $output; } if ($labels) { if ($label_ids) { $_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_', $name . '_' . $value)); $_output .= '<label for="' . $_id . '">'; } else { $_output .= '<label>'; } } $name = smarty_function_escape_special_chars($name); $value = smarty_function_escape_special_chars($value); if ($escape) { $output = smarty_function_escape_special_chars($output); } $_output .= '<input type="checkbox" name="' . $name . '[]" value="' . $value . '"'; if ($labels && $label_ids) { $_output .= ' id="' . $_id . '"'; } if (is_array($selected)) { if (isset($selected[$value])) { $_output .= ' checked="checked"'; } } elseif ($value === $selected) { $_output .= ' checked="checked"'; } $_output .= $extra . ' />' . $output; if ($labels) { $_output .= '</label>'; } $_output .= $separator; return $_output; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.html_checkboxes.php
PHP
asf20
7,562
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty noprint modifier plugin * * Type: modifier<br> * Name: noprint<br> * Purpose: return an empty string * * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_noprint($params, $compiler) { return "''"; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.noprint.php
PHP
asf20
431
<?php /** * Smarty shared plugin * * @package Smarty * @subpackage PluginsShared */ if (version_compare(PHP_VERSION, '5.2.3', '>=')) { /** * 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 $string text that should by escaped * @return string */ function smarty_function_escape_special_chars($string) { if (!is_array($string)) { $string = htmlspecialchars($string, ENT_COMPAT, Smarty::$_CHARSET, false); } return $string; } } else { /** * 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 $string text that should by escaped * @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; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/shared.escape_special_chars.php
PHP
asf20
1,720
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty from_charset modifier plugin * * Type: modifier<br> * Name: from_charset<br> * Purpose: convert character encoding from $charset to internal encoding * * @author Rodney Rehm * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_from_charset($params, $compiler) { if (!Smarty::$_MBSTRING) { // FIXME: (rodneyrehm) shouldn't this throw an error? return $params[0]; } if (!isset($params[1])) { $params[1] = '"ISO-8859-1"'; } return 'mb_convert_encoding(' . $params[0] . ', "' . addslashes(Smarty::$_CHARSET) . '", ' . $params[1] . ')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.from_charset.php
PHP
asf20
794
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * @ignore */ require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'); /** * @ignore */ require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'); /** * Smarty {html_select_time} function plugin * * Type: function<br> * Name: html_select_time<br> * Purpose: Prints the dropdowns for time selection * * @link http://www.smarty.net/manual/en/language.function.html.select.time.php {html_select_time} * (Smarty online manual) * @author Roberto Berto <roberto@berto.net> * @author Monte Ohrt <monte AT ohrt DOT com> * @param array $params parameters * @param Smarty_Internal_Template $template template object * @return string * @uses smarty_make_timestamp() */ function smarty_function_html_select_time($params, $template) { $prefix = "Time_"; $field_array = null; $field_separator = "\n"; $option_separator = "\n"; $time = null; $display_hours = true; $display_minutes = true; $display_seconds = true; $display_meridian = true; $hour_format = '%02d'; $hour_value_format = '%02d'; $minute_format = '%02d'; $minute_value_format = '%02d'; $second_format = '%02d'; $second_value_format = '%02d'; $hour_size = null; $minute_size = null; $second_size = null; $meridian_size = null; $all_empty = null; $hour_empty = null; $minute_empty = null; $second_empty = null; $meridian_empty = null; $all_id = null; $hour_id = null; $minute_id = null; $second_id = null; $meridian_id = null; $use_24_hours = true; $minute_interval = 1; $second_interval = 1; $extra_attrs = ''; $all_extra = null; $hour_extra = null; $minute_extra = null; $second_extra = null; $meridian_extra = null; foreach ($params as $_key => $_value) { switch ($_key) { case 'time': if (!is_array($_value) && $_value !== null) { $time = smarty_make_timestamp($_value); } break; case 'prefix': case 'field_array': case 'field_separator': case 'option_separator': case 'all_extra': case 'hour_extra': case 'minute_extra': case 'second_extra': case 'meridian_extra': case 'all_empty': case 'hour_empty': case 'minute_empty': case 'second_empty': case 'meridian_empty': case 'all_id': case 'hour_id': case 'minute_id': case 'second_id': case 'meridian_id': case 'hour_format': case 'hour_value_format': case 'minute_format': case 'minute_value_format': case 'second_format': case 'second_value_format': $$_key = (string)$_value; break; case 'display_hours': case 'display_minutes': case 'display_seconds': case 'display_meridian': case 'use_24_hours': $$_key = (bool)$_value; break; case 'minute_interval': case 'second_interval': case 'hour_size': case 'minute_size': case 'second_size': case 'meridian_size': $$_key = (int)$_value; break; default: if (!is_array($_value)) { $extra_attrs .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_value) . '"'; } else { trigger_error("html_select_date: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (isset($params['time']) && is_array($params['time'])) { if (isset($params['time'][$prefix . 'Hour'])) { // $_REQUEST[$field_array] given foreach (array('H' => 'Hour', 'i' => 'Minute', 's' => 'Second') as $_elementKey => $_elementName) { $_variableName = '_' . strtolower($_elementName); $$_variableName = isset($params['time'][$prefix . $_elementName]) ? $params['time'][$prefix . $_elementName] : date($_elementKey); } $_meridian = isset($params['time'][$prefix . 'Meridian']) ? (' ' . $params['time'][$prefix . 'Meridian']) : ''; $time = strtotime( $_hour . ':' . $_minute . ':' . $_second . $_meridian ); list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time)); } elseif (isset($params['time'][$field_array][$prefix . 'Hour'])) { // $_REQUEST given foreach (array('H' => 'Hour', 'i' => 'Minute', 's' => 'Second') as $_elementKey => $_elementName) { $_variableName = '_' . strtolower($_elementName); $$_variableName = isset($params['time'][$field_array][$prefix . $_elementName]) ? $params['time'][$field_array][$prefix . $_elementName] : date($_elementKey); } $_meridian = isset($params['time'][$field_array][$prefix . 'Meridian']) ? (' ' . $params['time'][$field_array][$prefix . 'Meridian']) : ''; $time = strtotime( $_hour . ':' . $_minute . ':' . $_second . $_meridian ); list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time)); } else { // no date found, use NOW list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d')); } } elseif ($time === null) { if (array_key_exists('time', $params)) { $_hour = $_minute = $_second = $time = null; } else { list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s')); } } else { list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time)); } // generate hour <select> if ($display_hours) { $_html_hours = ''; $_extra = ''; $_name = $field_array ? ($field_array . '[' . $prefix . 'Hour]') : ($prefix . 'Hour'); if ($all_extra) { $_extra .= ' ' . $all_extra; } if ($hour_extra) { $_extra .= ' ' . $hour_extra; } $_html_hours = '<select name="' . $_name . '"'; if ($hour_id !== null || $all_id !== null) { $_html_hours .= ' id="' . smarty_function_escape_special_chars( $hour_id !== null ? ( $hour_id ? $hour_id : $_name ) : ( $all_id ? ($all_id . $_name) : $_name ) ) . '"'; } if ($hour_size) { $_html_hours .= ' size="' . $hour_size . '"'; } $_html_hours .= $_extra . $extra_attrs . '>' . $option_separator; if (isset($hour_empty) || isset($all_empty)) { $_html_hours .= '<option value="">' . ( isset($hour_empty) ? $hour_empty : $all_empty ) . '</option>' . $option_separator; } $start = $use_24_hours ? 0 : 1; $end = $use_24_hours ? 23 : 12; for ($i=$start; $i <= $end; $i++) { $_val = sprintf('%02d', $i); $_text = $hour_format == '%02d' ? $_val : sprintf($hour_format, $i); $_value = $hour_value_format == '%02d' ? $_val : sprintf($hour_value_format, $i); if (!$use_24_hours) { $_hour12 = $_hour == 0 ? 12 : ($_hour <= 12 ? $_hour : $_hour -12); } $selected = $_hour !== null ? ($use_24_hours ? $_hour == $_val : $_hour12 == $_val) : null; $_html_hours .= '<option value="' . $_value . '"' . ($selected ? ' selected="selected"' : '') . '>' . $_text . '</option>' . $option_separator; } $_html_hours .= '</select>'; } // generate minute <select> if ($display_minutes) { $_html_minutes = ''; $_extra = ''; $_name = $field_array ? ($field_array . '[' . $prefix . 'Minute]') : ($prefix . 'Minute'); if ($all_extra) { $_extra .= ' ' . $all_extra; } if ($minute_extra) { $_extra .= ' ' . $minute_extra; } $_html_minutes = '<select name="' . $_name . '"'; if ($minute_id !== null || $all_id !== null) { $_html_minutes .= ' id="' . smarty_function_escape_special_chars( $minute_id !== null ? ( $minute_id ? $minute_id : $_name ) : ( $all_id ? ($all_id . $_name) : $_name ) ) . '"'; } if ($minute_size) { $_html_minutes .= ' size="' . $minute_size . '"'; } $_html_minutes .= $_extra . $extra_attrs . '>' . $option_separator; if (isset($minute_empty) || isset($all_empty)) { $_html_minutes .= '<option value="">' . ( isset($minute_empty) ? $minute_empty : $all_empty ) . '</option>' . $option_separator; } $selected = $_minute !== null ? ($_minute - $_minute % $minute_interval) : null; for ($i=0; $i <= 59; $i += $minute_interval) { $_val = sprintf('%02d', $i); $_text = $minute_format == '%02d' ? $_val : sprintf($minute_format, $i); $_value = $minute_value_format == '%02d' ? $_val : sprintf($minute_value_format, $i); $_html_minutes .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') . '>' . $_text . '</option>' . $option_separator; } $_html_minutes .= '</select>'; } // generate second <select> if ($display_seconds) { $_html_seconds = ''; $_extra = ''; $_name = $field_array ? ($field_array . '[' . $prefix . 'Second]') : ($prefix . 'Second'); if ($all_extra) { $_extra .= ' ' . $all_extra; } if ($second_extra) { $_extra .= ' ' . $second_extra; } $_html_seconds = '<select name="' . $_name . '"'; if ($second_id !== null || $all_id !== null) { $_html_seconds .= ' id="' . smarty_function_escape_special_chars( $second_id !== null ? ( $second_id ? $second_id : $_name ) : ( $all_id ? ($all_id . $_name) : $_name ) ) . '"'; } if ($second_size) { $_html_seconds .= ' size="' . $second_size . '"'; } $_html_seconds .= $_extra . $extra_attrs . '>' . $option_separator; if (isset($second_empty) || isset($all_empty)) { $_html_seconds .= '<option value="">' . ( isset($second_empty) ? $second_empty : $all_empty ) . '</option>' . $option_separator; } $selected = $_second !== null ? ($_second - $_second % $second_interval) : null; for ($i=0; $i <= 59; $i += $second_interval) { $_val = sprintf('%02d', $i); $_text = $second_format == '%02d' ? $_val : sprintf($second_format, $i); $_value = $second_value_format == '%02d' ? $_val : sprintf($second_value_format, $i); $_html_seconds .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') . '>' . $_text . '</option>' . $option_separator; } $_html_seconds .= '</select>'; } // generate meridian <select> if ($display_meridian && !$use_24_hours) { $_html_meridian = ''; $_extra = ''; $_name = $field_array ? ($field_array . '[' . $prefix . 'Meridian]') : ($prefix . 'Meridian'); if ($all_extra) { $_extra .= ' ' . $all_extra; } if ($meridian_extra) { $_extra .= ' ' . $meridian_extra; } $_html_meridian = '<select name="' . $_name . '"'; if ($meridian_id !== null || $all_id !== null) { $_html_meridian .= ' id="' . smarty_function_escape_special_chars( $meridian_id !== null ? ( $meridian_id ? $meridian_id : $_name ) : ( $all_id ? ($all_id . $_name) : $_name ) ) . '"'; } if ($meridian_size) { $_html_meridian .= ' size="' . $meridian_size . '"'; } $_html_meridian .= $_extra . $extra_attrs . '>' . $option_separator; if (isset($meridian_empty) || isset($all_empty)) { $_html_meridian .= '<option value="">' . ( isset($meridian_empty) ? $meridian_empty : $all_empty ) . '</option>' . $option_separator; } $_html_meridian .= '<option value="am"'. ($_hour < 12 ? ' selected="selected"' : '') .'>AM</option>' . $option_separator . '<option value="pm"'. ($_hour < 12 ? '' : ' selected="selected"') .'>PM</option>' . $option_separator . '</select>'; } $_html = ''; foreach (array('_html_hours', '_html_minutes', '_html_seconds', '_html_meridian') as $k) { if (isset($$k)) { if ($_html) { $_html .= $field_separator; } $_html .= $$k; } } return $_html; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.html_select_time.php
PHP
asf20
13,614
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * 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> * Examples: {html_image file="/images/masthead.gif"}<br> * Output: <img src="/images/masthead.gif" width=400 height=23><br> * Params: * <pre> * - file - (required) - file (and path) of image * - height - (optional) - image height (default actual height) * - width - (optional) - image width (default actual width) * - basedir - (optional) - base directory for absolute paths, default is environment variable DOCUMENT_ROOT * - path_prefix - prefix for path output (optional, default empty) * </pre> * * @link http://www.smarty.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> * @version 1.0 * @param array $params parameters * @param Smarty_Internal_Template $template template object * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_image($params, $template) { require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'); $alt = ''; $file = ''; $height = ''; $width = ''; $extra = ''; $prefix = ''; $suffix = ''; $path_prefix = ''; $basedir = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['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 { throw new SmartyException ("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 { throw new SmartyException ("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (empty($file)) { trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE); return; } if ($file[0] == '/') { $_image_path = $basedir . $file; } else { $_image_path = $file; } // strip file protocol if (stripos($params['file'], 'file://') === 0) { $params['file'] = substr($params['file'], 7); } $protocol = strpos($params['file'], '://'); if ($protocol !== false) { $protocol = strtolower(substr($params['file'], 0, $protocol)); } if (isset($template->smarty->security_policy)) { if ($protocol) { // remote resource (or php stream, …) if(!$template->smarty->security_policy->isTrustedUri($params['file'])) { return; } } else { // local file if(!$template->smarty->security_policy->isTrustedResourceDir($params['file'])) { return; } } } if (!isset($params['width']) || !isset($params['height'])) { // FIXME: (rodneyrehm) getimagesize() loads the complete file off a remote resource, use custom [jpg,png,gif]header reader! if (!$_image_data = @getimagesize($_image_path)) { if (!file_exists($_image_path)) { trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE); return; } else if (!is_readable($_image_path)) { trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE); return; } else { trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE); return; } } if (!isset($params['width'])) { $width = $_image_data[0]; } if (!isset($params['height'])) { $height = $_image_data[1]; } } if (isset($params['dpi'])) { if (strstr($_SERVER['HTTP_USER_AGENT'], 'Mac')) { // FIXME: (rodneyrehm) wrong dpi assumption // don't know who thought this up… even if it was true in 1998, it's definitely wrong in 2011. $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; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.html_image.php
PHP
asf20
5,471
<?php /** * Smarty plugin * @package Smarty * @subpackage PluginsModifier */ /** * 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> * @author Uwe Tews * @param string $string input string * @param string $search text to search for * @param string $replace replacement text * @return string */ function smarty_modifier_replace($string, $search, $replace) { if (Smarty::$_MBSTRING) { require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php'); return smarty_mb_str_replace($search, $replace, $string); } return str_replace($search, $replace, $string); } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifier.replace.php
PHP
asf20
866
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * @ignore */ require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'); /** * @ignore */ require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'); /** * Smarty {html_select_date} plugin * * Type: function<br> * Name: html_select_date<br> * Purpose: Prints the dropdowns for date selection. * * ChangeLog: * <pre> * - 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) * - 2.0 complete rewrite for performance, * added attributes month_names, *_id * </pre> * * @link http://www.smarty.net/manual/en/language.function.html.select.date.php {html_select_date} * (Smarty online manual) * @version 2.0 * @author Andrei Zmievski * @author Monte Ohrt <monte at ohrt dot com> * @author Rodney Rehm * @param array $params parameters * @param Smarty_Internal_Template $template template object * @return string */ function smarty_function_html_select_date($params, $template) { // generate timestamps used for month names only static $_month_timestamps = null; static $_current_year = null; if ($_month_timestamps === null) { $_current_year = date('Y'); $_month_timestamps = array(); for ($i = 1; $i <= 12; $i++) { $_month_timestamps[$i] = mktime(0, 0, 0, $i, 1, 2000); } } /* Default values. */ $prefix = "Date_"; $start_year = null; $end_year = null; $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"; $option_separator = "\n"; $time = null; // $all_empty = null; // $day_empty = null; // $month_empty = null; // $year_empty = null; $extra_attrs = ''; $all_id = null; $day_id = null; $month_id = null; $year_id = null; foreach ($params as $_key => $_value) { switch ($_key) { case 'time': if (!is_array($_value) && $_value !== null) { $time = smarty_make_timestamp($_value); } break; case 'month_names': if (is_array($_value) && count($_value) == 12) { $$_key = $_value; } else { trigger_error("html_select_date: month_names must be an array of 12 strings", E_USER_NOTICE); } break; case 'prefix': case 'field_array': case 'start_year': case 'end_year': case 'day_format': case 'day_value_format': case 'month_format': case 'month_value_format': 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 'option_separator': case 'all_empty': case 'month_empty': case 'day_empty': case 'year_empty': case 'all_id': case 'month_id': case 'day_id': case 'year_id': $$_key = (string)$_value; 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 { trigger_error("html_select_date: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } // Note: date() is faster than strftime() // Note: explode(date()) is faster than date() date() date() if (isset($params['time']) && is_array($params['time'])) { if (isset($params['time'][$prefix . 'Year'])) { // $_REQUEST[$field_array] given foreach (array('Y' => 'Year', 'm' => 'Month', 'd' => 'Day') as $_elementKey => $_elementName) { $_variableName = '_' . strtolower($_elementName); $$_variableName = isset($params['time'][$prefix . $_elementName]) ? $params['time'][$prefix . $_elementName] : date($_elementKey); } $time = mktime(0, 0, 0, $_month, $_day, $_year); } elseif (isset($params['time'][$field_array][$prefix . 'Year'])) { // $_REQUEST given foreach (array('Y' => 'Year', 'm' => 'Month', 'd' => 'Day') as $_elementKey => $_elementName) { $_variableName = '_' . strtolower($_elementName); $$_variableName = isset($params['time'][$field_array][$prefix . $_elementName]) ? $params['time'][$field_array][$prefix . $_elementName] : date($_elementKey); } $time = mktime(0, 0, 0, $_month, $_day, $_year); } else { // no date found, use NOW list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d')); } } elseif ($time === null) { if (array_key_exists('time', $params)) { $_year = $_month = $_day = $time = null; } else { list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d')); } } else { list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d', $time)); } // make syntax "+N" or "-N" work with $start_year and $end_year // Note preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match) is slower than trim+substr foreach (array('start', 'end') as $key) { $key .= '_year'; $t = $$key; if ($t === null) { $$key = (int)$_current_year; } else if ($t[0] == '+') { $$key = (int)($_current_year + trim(substr($t, 1))); } else if ($t[0] == '-') { $$key = (int)($_current_year - trim(substr($t, 1))); } else { $$key = (int)$$key; } } // flip for ascending or descending if (($start_year > $end_year && !$reverse_years) || ($start_year < $end_year && $reverse_years)) { $t = $end_year; $end_year = $start_year; $start_year = $t; } // generate year <select> or <input> if ($display_years) { $_html_years = ''; $_extra = ''; $_name = $field_array ? ($field_array . '[' . $prefix . 'Year]') : ($prefix . 'Year'); if ($all_extra) { $_extra .= ' ' . $all_extra; } if ($year_extra) { $_extra .= ' ' . $year_extra; } if ($year_as_text) { $_html_years = '<input type="text" name="' . $_name . '" value="' . $_year . '" size="4" maxlength="4"' . $_extra . $extra_attrs . ' />'; } else { $_html_years = '<select name="' . $_name . '"'; if ($year_id !== null || $all_id !== null) { $_html_years .= ' id="' . smarty_function_escape_special_chars( $year_id !== null ? ( $year_id ? $year_id : $_name ) : ( $all_id ? ($all_id . $_name) : $_name ) ) . '"'; } if ($year_size) { $_html_years .= ' size="' . $year_size . '"'; } $_html_years .= $_extra . $extra_attrs . '>' . $option_separator; if (isset($year_empty) || isset($all_empty)) { $_html_years .= '<option value="">' . ( isset($year_empty) ? $year_empty : $all_empty ) . '</option>' . $option_separator; } $op = $start_year > $end_year ? -1 : 1; for ($i=$start_year; $op > 0 ? $i <= $end_year : $i >= $end_year; $i += $op) { $_html_years .= '<option value="' . $i . '"' . ($_year == $i ? ' selected="selected"' : '') . '>' . $i . '</option>' . $option_separator; } $_html_years .= '</select>'; } } // generate month <select> or <input> if ($display_months) { $_html_month = ''; $_extra = ''; $_name = $field_array ? ($field_array . '[' . $prefix . 'Month]') : ($prefix . 'Month'); if ($all_extra) { $_extra .= ' ' . $all_extra; } if ($month_extra) { $_extra .= ' ' . $month_extra; } $_html_months = '<select name="' . $_name . '"'; if ($month_id !== null || $all_id !== null) { $_html_months .= ' id="' . smarty_function_escape_special_chars( $month_id !== null ? ( $month_id ? $month_id : $_name ) : ( $all_id ? ($all_id . $_name) : $_name ) ) . '"'; } if ($month_size) { $_html_months .= ' size="' . $month_size . '"'; } $_html_months .= $_extra . $extra_attrs . '>' . $option_separator; if (isset($month_empty) || isset($all_empty)) { $_html_months .= '<option value="">' . ( isset($month_empty) ? $month_empty : $all_empty ) . '</option>' . $option_separator; } for ($i = 1; $i <= 12; $i++) { $_val = sprintf('%02d', $i); $_text = isset($month_names) ? smarty_function_escape_special_chars($month_names[$i]) : ($month_format == "%m" ? $_val : strftime($month_format, $_month_timestamps[$i])); $_value = $month_value_format == "%m" ? $_val : strftime($month_value_format, $_month_timestamps[$i]); $_html_months .= '<option value="' . $_value . '"' . ($_val == $_month ? ' selected="selected"' : '') . '>' . $_text . '</option>' . $option_separator; } $_html_months .= '</select>'; } // generate day <select> or <input> if ($display_days) { $_html_day = ''; $_extra = ''; $_name = $field_array ? ($field_array . '[' . $prefix . 'Day]') : ($prefix . 'Day'); if ($all_extra) { $_extra .= ' ' . $all_extra; } if ($day_extra) { $_extra .= ' ' . $day_extra; } $_html_days = '<select name="' . $_name . '"'; if ($day_id !== null || $all_id !== null) { $_html_days .= ' id="' . smarty_function_escape_special_chars( $day_id !== null ? ( $day_id ? $day_id : $_name ) : ( $all_id ? ($all_id . $_name) : $_name ) ) . '"'; } if ($day_size) { $_html_days .= ' size="' . $day_size . '"'; } $_html_days .= $_extra . $extra_attrs . '>' . $option_separator; if (isset($day_empty) || isset($all_empty)) { $_html_days .= '<option value="">' . ( isset($day_empty) ? $day_empty : $all_empty ) . '</option>' . $option_separator; } for ($i = 1; $i <= 31; $i++) { $_val = sprintf('%02d', $i); $_text = $day_format == '%02d' ? $_val : sprintf($day_format, $i); $_value = $day_value_format == '%02d' ? $_val : sprintf($day_value_format, $i); $_html_days .= '<option value="' . $_value . '"' . ($_val == $_day ? ' selected="selected"' : '') . '>' . $_text . '</option>' . $option_separator; } $_html_days .= '</select>'; } // order the fields for output $_html = ''; for ($i=0; $i <= 2; $i++) { switch ($field_order[$i]) { case 'Y': case 'y': if (isset($_html_years)) { if ($_html) { $_html .= $field_separator; } $_html .= $_html_years; } break; case 'm': case 'M': if (isset($_html_months)) { if ($_html) { $_html .= $field_separator; } $_html .= $_html_months; } break; case 'd': case 'D': if (isset($_html_days)) { if ($_html) { $_html .= $field_separator; } $_html .= $_html_days; } break; } } return $_html; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.html_select_date.php
PHP
asf20
14,961
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFilter */ /** * Smarty trimwhitespace outputfilter plugin * * Trim unnecessary whitespace from HTML markup. * * @author Rodney Rehm * @param string $source input string * @param Smarty_Internal_Template $smarty Smarty object * @return string filtered output */ function smarty_outputfilter_trimwhitespace($source, Smarty_Internal_Template $smarty) { $store = array(); $_store = 0; $_offset = 0; // Unify Line-Breaks to \n $source = preg_replace("/\015\012|\015|\012/", "\n", $source); // capture Internet Explorer Conditional Comments if (preg_match_all('#<!--\[[^\]]+\]>.*?<!\[[^\]]+\]-->#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { foreach ($matches as $match) { $store[] = $match[0][0]; $_length = strlen($match[0][0]); $replace = '@!@SMARTY:' . $_store . ':SMARTY@!@'; $source = substr_replace($source, $replace, $match[0][1] - $_offset, $_length); $_offset += $_length - strlen($replace); $_store++; } } // Strip all HTML-Comments $source = preg_replace( '#<!--.*?-->#ms', '', $source ); // capture html elements not to be messed with $_offset = 0; if (preg_match_all('#<(script|pre|textarea)[^>]*>.*?</\\1>#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { foreach ($matches as $match) { $store[] = $match[0][0]; $_length = strlen($match[0][0]); $replace = '@!@SMARTY:' . $_store . ':SMARTY@!@'; $source = substr_replace($source, $replace, $match[0][1] - $_offset, $_length); $_offset += $_length - strlen($replace); $_store++; } } $expressions = array( // replace multiple spaces between tags by a single space // can't remove them entirely, becaue that might break poorly implemented CSS display:inline-block elements '#(:SMARTY@!@|>)\s+(?=@!@SMARTY:|<)#s' => '\1 \2', // remove spaces between attributes (but not in attribute values!) '#(([a-z0-9]\s*=\s*(["\'])[^\3]*?\3)|<[a-z0-9_]+)\s+([a-z/>])#is' => '\1 \4', // note: for some very weird reason trim() seems to remove spaces inside attributes. // maybe a \0 byte or something is interfering? '#^\s+<#Ss' => '<', '#>\s+$#Ss' => '>', ); $source = preg_replace( array_keys($expressions), array_values($expressions), $source ); // note: for some very weird reason trim() seems to remove spaces inside attributes. // maybe a \0 byte or something is interfering? // $source = trim( $source ); // capture html elements not to be messed with $_offset = 0; if (preg_match_all('#@!@SMARTY:([0-9]+):SMARTY@!@#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { foreach ($matches as $match) { $store[] = $match[0][0]; $_length = strlen($match[0][0]); $replace = array_shift($store); $source = substr_replace($source, $replace, $match[0][1] + $_offset, $_length); $_offset += strlen($replace) - $_length; $_store++; } } return $source; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/outputfilter.trimwhitespace.php
PHP
asf20
3,380
<?php /** * Smarty shared plugin * * @package Smarty * @subpackage PluginsShared */ if (!function_exists('smarty_mb_str_replace')) { /** * Multibyte string replace * * @param string $search the string to be searched * @param string $replace the replacement string * @param string $subject the source string * @param int &$count number of matches found * @return string replaced string * @author Rodney Rehm */ function smarty_mb_str_replace($search, $replace, $subject, &$count=0) { if (!is_array($search) && is_array($replace)) { return false; } if (is_array($subject)) { // call mb_replace for each single string in $subject foreach ($subject as &$string) { $string = &smarty_mb_str_replace($search, $replace, $string, $c); $count += $c; } } elseif (is_array($search)) { if (!is_array($replace)) { foreach ($search as &$string) { $subject = smarty_mb_str_replace($string, $replace, $subject, $c); $count += $c; } } else { $n = max(count($search), count($replace)); while ($n--) { $subject = smarty_mb_str_replace(current($search), current($replace), $subject, $c); $count += $c; next($search); next($replace); } } } else { $parts = mb_split(preg_quote($search), $subject); $count = count($parts) - 1; $subject = implode($replace, $parts); } return $subject; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/shared.mb_str_replace.php
PHP
asf20
1,801
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifier */ /** * Smarty truncate modifier plugin * * Type: modifier<br> * Name: truncate<br> * Purpose: Truncate a string to a certain length if necessary, * optionally splitting in the middle of a word, and * appending the $etc string or inserting $etc into the middle. * * @link http://smarty.php.net/manual/en/language.modifier.truncate.php truncate (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string $string input string * @param integer $length length of truncated text * @param string $etc end string * @param boolean $break_words truncate at word boundary * @param boolean $middle truncate in the middle of text * @return string truncated string */ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false) { if ($length == 0) return ''; if (Smarty::$_MBSTRING) { if (mb_strlen($string, Smarty::$_CHARSET) > $length) { $length -= min($length, mb_strlen($etc, Smarty::$_CHARSET)); if (!$break_words && !$middle) { $string = preg_replace('/\s+?(\S+)?$/' . Smarty::$_UTF8_MODIFIER, '', mb_substr($string, 0, $length + 1, Smarty::$_CHARSET)); } if (!$middle) { return mb_substr($string, 0, $length, Smarty::$_CHARSET) . $etc; } return mb_substr($string, 0, $length / 2, Smarty::$_CHARSET) . $etc . mb_substr($string, - $length / 2, $length, Smarty::$_CHARSET); } return $string; } // no MBString fallback if (isset($string[$length])) { $length -= min($length, strlen($etc)); if (!$break_words && !$middle) { $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1)); } if (!$middle) { return substr($string, 0, $length) . $etc; } return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2); } return $string; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifier.truncate.php
PHP
asf20
2,200
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifier */ /** * Smarty regex_replace modifier plugin * * Type: modifier<br> * Name: regex_replace<br> * Purpose: regular expression search/replace * * @link http://smarty.php.net/manual/en/language.modifier.regex.replace.php * regex_replace (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string $string input string * @param string|array $search regular expression(s) to search for * @param string|array $replace string(s) that should be replaced * @return string */ function smarty_modifier_regex_replace($string, $search, $replace) { if(is_array($search)) { foreach($search as $idx => $s) { $search[$idx] = _smarty_regex_replace_check($s); } } else { $search = _smarty_regex_replace_check($search); } return preg_replace($search, $replace, $string); } /** * @param string $search string(s) that should be replaced * @return string * @ignore */ function _smarty_regex_replace_check($search) { // null-byte injection detection // anything behind the first null-byte is ignored if (($pos = strpos($search,"\0")) !== false) { $search = substr($search,0,$pos); } // remove eval-modifier from $search if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[1], 'e') !== false)) { $search = substr($search, 0, -strlen($match[1])) . preg_replace('![e\s]+!', '', $match[1]); } return $search; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifier.regex_replace.php
PHP
asf20
1,614
<?php /** * Smarty shared plugin * * @package Smarty * @subpackage PluginsShared */ /** * convert characters to their decimal unicode equivalents * * @link http://www.ibm.com/developerworks/library/os-php-unicode/index.html#listing3 for inspiration * @param string $string characters to calculate unicode of * @param string $encoding encoding of $string, if null mb_internal_encoding() is used * @return array sequence of unicodes * @author Rodney Rehm */ function smarty_mb_to_unicode($string, $encoding=null) { if ($encoding) { $expanded = mb_convert_encoding($string, "UTF-32BE", $encoding); } else { $expanded = mb_convert_encoding($string, "UTF-32BE"); } return unpack("N*", $expanded); } /** * convert unicodes to the character of given encoding * * @link http://www.ibm.com/developerworks/library/os-php-unicode/index.html#listing3 for inspiration * @param integer|array $unicode single unicode or list of unicodes to convert * @param string $encoding encoding of returned string, if null mb_internal_encoding() is used * @return string unicode as character sequence in given $encoding * @author Rodney Rehm */ function smarty_mb_from_unicode($unicode, $encoding=null) { $t = ''; if (!$encoding) { $encoding = mb_internal_encoding(); } foreach((array) $unicode as $utf32be) { $character = pack("N*", $utf32be); $t .= mb_convert_encoding($character, $encoding, "UTF-32BE"); } return $t; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/shared.mb_unicode.php
PHP
asf20
1,558
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty upper modifier plugin * * Type: modifier<br> * Name: lower<br> * Purpose: convert string to uppercase * * @link http://smarty.php.net/manual/en/language.modifier.upper.php lower (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_upper($params, $compiler) { if (Smarty::$_MBSTRING) { return 'mb_strtoupper(' . $params[0] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')' ; } // no MBString fallback return 'strtoupper(' . $params[0] . ')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.upper.php
PHP
asf20
723
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty string_format modifier plugin * * Type: modifier<br> * Name: string_format<br> * Purpose: format strings via sprintf * * @link http://www.smarty.net/manual/en/language.modifier.string.format.php string_format (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_string_format($params, $compiler) { return 'sprintf(' . $params[1] . ',' . $params[0] . ')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.string_format.php
PHP
asf20
610
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty count_characters modifier plugin * * Type: modifier<br> * Name: count_characteres<br> * Purpose: count the number of characters in a text * * @link http://www.smarty.net/manual/en/language.modifier.count.characters.php count_characters (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_count_characters($params, $compiler) { if (!isset($params[1]) || $params[1] != 'true') { return 'preg_match_all(\'/[^\s]/' . Smarty::$_UTF8_MODIFIER . '\',' . $params[0] . ', $tmp)'; } if (Smarty::$_MBSTRING) { return 'mb_strlen(' . $params[0] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')'; } // no MBString fallback return 'strlen(' . $params[0] . ')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.count_characters.php
PHP
asf20
944
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty unescape modifier plugin * * Type: modifier<br> * Name: unescape<br> * Purpose: unescape html entities * * @author Rodney Rehm * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_unescape($params, $compiler) { if (!isset($params[1])) { $params[1] = 'html'; } if (!isset($params[2])) { $params[2] = '\'' . addslashes(Smarty::$_CHARSET) . '\''; } else { $params[2] = "'" . $params[2] . "'"; } switch (trim($params[1], '"\'')) { case 'entity': return 'mb_convert_encoding(' . $params[0] . ', ' . $params[2] . ', \'HTML-ENTITIES\')'; case 'htmlall': if (Smarty::$_MBSTRING) { return 'mb_convert_encoding(' . $params[0] . ', ' . $params[2] . ', \'HTML-ENTITIES\')'; } return 'html_entity_decode(' . $params[0] . ', ENT_QUOTES, ' . $params[2] . ')'; case 'html': return 'htmlspecialchars_decode(' . $params[0] . ', ENT_QUOTES)'; default: return $params[0]; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.unescape.php
PHP
asf20
1,259
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty cat modifier plugin * * Type: modifier<br> * Name: cat<br> * Date: Feb 24, 2003<br> * Purpose: catenate a value to a variable<br> * Input: string to catenate<br> * Example: {$var|cat:"foo"} * * @link http://smarty.php.net/manual/en/language.modifier.cat.php cat * (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_cat($params, $compiler) { return '('.implode(').(', $params).')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.cat.php
PHP
asf20
665
<?php /** * Smarty shared plugin * * @package Smarty * @subpackage PluginsShared */ if(!function_exists('smarty_mb_wordwrap')) { /** * Wrap a string to a given number of characters * * @link http://php.net/manual/en/function.wordwrap.php for similarity * @param string $str the string to wrap * @param int $width the width of the output * @param string $break the character used to break the line * @param boolean $cut ignored parameter, just for the sake of * @return string wrapped string * @author Rodney Rehm */ function smarty_mb_wordwrap($str, $width=75, $break="\n", $cut=false) { // break words into tokens using white space as a delimiter $tokens = preg_split('!(\s)!S' . Smarty::$_UTF8_MODIFIER, $str, -1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE); $length = 0; $t = ''; $_previous = false; foreach ($tokens as $_token) { $token_length = mb_strlen($_token, Smarty::$_CHARSET); $_tokens = array($_token); if ($token_length > $width) { // remove last space $t = mb_substr($t, 0, -1, Smarty::$_CHARSET); $_previous = false; $length = 0; if ($cut) { $_tokens = preg_split('!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER, $_token, -1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE); // broken words go on a new line $t .= $break; } } foreach ($_tokens as $token) { $_space = !!preg_match('!^\s$!S' . Smarty::$_UTF8_MODIFIER, $token); $token_length = mb_strlen($token, Smarty::$_CHARSET); $length += $token_length; if ($length > $width) { // remove space before inserted break if ($_previous && $token_length < $width) { $t = mb_substr($t, 0, -1, Smarty::$_CHARSET); } // add the break before the token $t .= $break; $length = $token_length; // skip space after inserting a break if ($_space) { $length = 0; continue; } } else if ($token == "\n") { // hard break must reset counters $_previous = 0; $length = 0; } else { // remember if we had a space or not $_previous = $_space; } // add the token $t .= $token; } } return $t; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/shared.mb_wordwrap.php
PHP
asf20
2,909
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * Smarty {fetch} plugin * * Type: function<br> * Name: fetch<br> * Purpose: fetch file, web or ftp data and display results * * @link http://www.smarty.net/manual/en/language.function.fetch.php {fetch} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array $params parameters * @param Smarty_Internal_Template $template template object * @return string|null if the assign parameter is passed, Smarty assigns the result to a template variable */ function smarty_function_fetch($params, $template) { if (empty($params['file'])) { trigger_error("[plugin] fetch parameter 'file' cannot be empty",E_USER_NOTICE); return; } // strip file protocol if (stripos($params['file'], 'file://') === 0) { $params['file'] = substr($params['file'], 7); } $protocol = strpos($params['file'], '://'); if ($protocol !== false) { $protocol = strtolower(substr($params['file'], 0, $protocol)); } if (isset($template->smarty->security_policy)) { if ($protocol) { // remote resource (or php stream, …) if(!$template->smarty->security_policy->isTrustedUri($params['file'])) { return; } } else { // local file if(!$template->smarty->security_policy->isTrustedResourceDir($params['file'])) { return; } } } $content = ''; if ($protocol == 'http') { // 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::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)) { trigger_error("[plugin] invalid header format '".$param_value."'",E_USER_NOTICE); 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 { trigger_error("[plugin] invalid value for attribute '".$param_key."'",E_USER_NOTICE); 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 { trigger_error("[plugin] invalid value for attribute '".$param_key."'",E_USER_NOTICE); return; } break; default: trigger_error("[plugin] unrecognized attribute '".$param_key."'",E_USER_NOTICE); 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) { trigger_error("[plugin] unable to fetch: $errstr ($errno)",E_USER_NOTICE); 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 = preg_split("!\r\n\r\n!",$content,2); $content = $csplit[1]; if(!empty($params['assign_headers'])) { $template->assign($params['assign_headers'],preg_split("!\r\n!",$csplit[0])); } } } else { trigger_error("[plugin fetch] unable to parse URL, check syntax",E_USER_NOTICE); return; } } else { $content = @file_get_contents($params['file']); if ($content === false) { throw new SmartyException("{fetch} cannot read resource '" . $params['file'] ."'"); } } if (!empty($params['assign'])) { $template->assign($params['assign'], $content); } else { return $content; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.fetch.php
PHP
asf20
8,166
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * Smarty {mailto} function plugin * * Type: function<br> * Name: mailto<br> * Date: May 21, 2002 * Purpose: automate mailto address link creation, and optionally encode them.<br> * Params: * <pre> * - address - (required) - e-mail address * - text - (optional) - text to display, default is address * - encode - (optional) - can be one of: * * none : no encoding (default) * * javascript : encode with javascript * * javascript_charcode : encode with javascript charcode * * hex : encode with hexidecimal (no javascript) * - cc - (optional) - address(es) to carbon copy * - bcc - (optional) - address(es) to blind carbon copy * - subject - (optional) - e-mail subject * - newsgroups - (optional) - newsgroup(s) to post to * - followupto - (optional) - address(es) to follow up to * - extra - (optional) - extra tags for the href link * </pre> * Examples: * <pre> * {mailto address="me@domain.com"} * {mailto address="me@domain.com" encode="javascript"} * {mailto address="me@domain.com" encode="hex"} * {mailto address="me@domain.com" subject="Hello to you!"} * {mailto address="me@domain.com" cc="you@domain.com,they@domain.com"} * {mailto address="me@domain.com" extra='class="mailto"'} * </pre> * * @link http://www.smarty.net/manual/en/language.function.mailto.php {mailto} * (Smarty online manual) * @version 1.2 * @author Monte Ohrt <monte at ohrt dot com> * @author credits to Jason Sweat (added cc, bcc and subject functionality) * @param array $params parameters * @param Smarty_Internal_Template $template template object * @return string */ function smarty_function_mailto($params, $template) { static $_allowed_encoding = array('javascript' => true, 'javascript_charcode' => true, 'hex' => true, 'none' => true); $extra = ''; if (empty($params['address'])) { trigger_error("mailto: missing 'address' parameter",E_USER_WARNING); return; } else { $address = $params['address']; } $text = $address; // netscape and mozilla do not decode %40 (@) in BCC field (bug?) // so, don't encode it. $search = array('%40', '%2C'); $replace = array('@', ','); $mail_parms = array(); foreach ($params as $var => $value) { switch ($var) { case 'cc': case 'bcc': case 'followupto': if (!empty($value)) $mail_parms[] = $var . '=' . str_replace($search, $replace, rawurlencode($value)); break; case 'subject': case 'newsgroups': $mail_parms[] = $var . '=' . rawurlencode($value); break; case 'extra': case 'text': $$var = $value; default: } } if ($mail_parms) { $address .= '?' . join('&', $mail_parms); } $encode = (empty($params['encode'])) ? 'none' : $params['encode']; if (!isset($_allowed_encoding[$encode])) { trigger_error("mailto: 'encode' parameter must be none, javascript, javascript_charcode or hex", E_USER_WARNING); return; } // FIXME: (rodneyrehm) document.write() excues me what? 1998 has passed! if ($encode == 'javascript') { $string = 'document.write(\'<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>\');'; $js_encode = ''; for ($x = 0, $_length = strlen($string); $x < $_length; $x++) { $js_encode .= '%' . bin2hex($string[$x]); } return '<script type="text/javascript">eval(unescape(\'' . $js_encode . '\'))</script>'; } elseif ($encode == 'javascript_charcode') { $string = '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>'; for($x = 0, $y = strlen($string); $x < $y; $x++) { $ord[] = ord($string[$x]); } $_ret = "<script type=\"text/javascript\" language=\"javascript\">\n" . "{document.write(String.fromCharCode(" . implode(',', $ord) . "))" . "}\n" . "</script>\n"; return $_ret; } elseif ($encode == 'hex') { preg_match('!^(.*)(\?.*)$!', $address, $match); if (!empty($match[2])) { trigger_error("mailto: hex encoding does not work with extra attributes. Try javascript.",E_USER_WARNING); return; } $address_encode = ''; for ($x = 0, $_length = strlen($address); $x < $_length; $x++) { if (preg_match('!\w!' . Smarty::$_UTF8_MODIFIER, $address[$x])) { $address_encode .= '%' . bin2hex($address[$x]); } else { $address_encode .= $address[$x]; } } $text_encode = ''; for ($x = 0, $_length = strlen($text); $x < $_length; $x++) { $text_encode .= '&#x' . bin2hex($text[$x]) . ';'; } $mailto = "&#109;&#97;&#105;&#108;&#116;&#111;&#58;"; return '<a href="' . $mailto . $address_encode . '" ' . $extra . '>' . $text_encode . '</a>'; } else { // no encoding return '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>'; } } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.mailto.php
PHP
asf20
5,608
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFilter */ /** * Smarty htmlspecialchars variablefilter plugin * * @param string $source input string * @param Smarty_Internal_Template $smarty Smarty object * @return string filtered output */ function smarty_variablefilter_htmlspecialchars($source, $smarty) { return htmlspecialchars($source, ENT_QUOTES, Smarty::$_CHARSET); } ?>
0x6a
trunk/application/libraries/smarty3/plugins/variablefilter.htmlspecialchars.php
PHP
asf20
452
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * Smarty {cycle} function plugin * * Type: function<br> * Name: cycle<br> * Date: May 3, 2002<br> * Purpose: cycle through given values<br> * Params: * <pre> * - 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. * </pre> * Examples:<br> * <pre> * {cycle values="#eeeeee,#d0d0d0d"} * {cycle name=row values="one,two,three" reset=true} * {cycle name=row} * </pre> * * @link http://www.smarty.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 $params parameters * @param Smarty_Internal_Template $template template object * @return string|null */ function smarty_function_cycle($params, $template) { 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 (!isset($params['values'])) { if(!isset($cycle_vars[$name]['values'])) { 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']; } if (isset($params['delimiter'])) { $cycle_vars[$name]['delimiter'] = $params['delimiter']; } elseif (!isset($cycle_vars[$name]['delimiter'])) { $cycle_vars[$name]['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; $template->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; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.cycle.php
PHP
asf20
3,355
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * 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> * Params: * <pre> * - name (optional) - string default "radio" * - values (required) - array * - options (required) - 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 * - escape (optional) - escape the content (not value), defaults to true * </pre> * 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 $params parameters * @param Smarty_Internal_Template $template template object * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_radios($params, $template) { require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'); $name = 'radio'; $values = null; $options = null; $selected = null; $separator = ''; $escape = true; $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)) { trigger_error('html_radios: the "' . $_key . '" attribute cannot be an array', E_USER_WARNING); } elseif (is_object($_val)) { if (method_exists($_val, "__toString")) { $selected = smarty_function_escape_special_chars((string) $_val->__toString()); } else { trigger_error("html_radios: selected attribute is an object of class '". get_class($_val) ."' without __toString() method", E_USER_NOTICE); } } else { $selected = (string) $_val; } break; case 'escape': 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': 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 { trigger_error("html_radios: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (!isset($options) && !isset($values)) { /* raise error here? */ return ''; } $_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, $escape); } } 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, $escape); } } if (!empty($params['assign'])) { $template->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, $escape) { $_output = ''; if (is_object($value)) { if (method_exists($value, "__toString")) { $value = (string) $value->__toString(); } else { trigger_error("html_options: value is an object of class '". get_class($value) ."' without __toString() method", E_USER_NOTICE); return ''; } } else { $value = (string) $value; } if (is_object($output)) { if (method_exists($output, "__toString")) { $output = (string) $output->__toString(); } else { trigger_error("html_options: output is an object of class '". get_class($output) ."' without __toString() method", E_USER_NOTICE); return ''; } } else { $output = (string) $output; } if ($labels) { if ($label_ids) { $_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_', $name . '_' . $value)); $_output .= '<label for="' . $_id . '">'; } else { $_output .= '<label>'; } } $name = smarty_function_escape_special_chars($name); $value = smarty_function_escape_special_chars($value); if ($escape) { $output = smarty_function_escape_special_chars($output); } $_output .= '<input type="radio" name="' . $name . '" value="' . $value . '"'; if ($labels && $label_ids) { $_output .= ' id="' . $_id . '"'; } if ($value === $selected) { $_output .= ' checked="checked"'; } $_output .= $extra . ' />' . $output; if ($labels) { $_output .= '</label>'; } $_output .= $separator; return $_output; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.html_radios.php
PHP
asf20
6,647
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty count_paragraphs modifier plugin * * Type: modifier<br> * Name: count_paragraphs<br> * Purpose: count the number of paragraphs in a text * * @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php * count_paragraphs (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_count_paragraphs($params, $compiler) { // count \r or \n characters return '(preg_match_all(\'#[\r\n]+#\', ' . $params[0] . ', $tmp)+1)'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.count_paragraphs.php
PHP
asf20
699
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty count_words modifier plugin * * Type: modifier<br> * Name: count_words<br> * Purpose: count the number of words in a text * * @link http://www.smarty.net/manual/en/language.modifier.count.words.php count_words (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_count_words($params, $compiler) { if (Smarty::$_MBSTRING) { // return 'preg_match_all(\'#[\w\pL]+#' . Smarty::$_UTF8_MODIFIER . '\', ' . $params[0] . ', $tmp)'; // expression taken from http://de.php.net/manual/en/function.str-word-count.php#85592 return 'preg_match_all(\'/\p{L}[\p{L}\p{Mn}\p{Pd}\\\'\x{2019}]*/' . Smarty::$_UTF8_MODIFIER . '\', ' . $params[0] . ', $tmp)'; } // no MBString fallback return 'str_word_count(' . $params[0] . ')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.count_words.php
PHP
asf20
1,005
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ /** * 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> * Params: * <pre> * - loop - array to loop through * - cols - number of columns, comma separated list of column names * or array of column 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 column by column otherwise) * </pre> * 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://www.smarty.net/manual/en/language.function.html.table.php {html_table} * (Smarty online manual) * @param array $params parameters * @param Smarty_Internal_Template $template template object * @return string */ function smarty_function_html_table($params, $template) { $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 = ''; $loop = null; if (!isset($params['loop'])) { trigger_error("html_table: missing 'loop' parameter",E_USER_WARNING); 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 : ''; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/function.html_table.php
PHP
asf20
5,599
<?php /** * Smarty plugin * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty indent modifier plugin * * Type: modifier<br> * Name: indent<br> * Purpose: indent lines of text * * @link http://www.smarty.net/manual/en/language.modifier.indent.php indent (Smarty online manual) * @author Uwe Tews * @param array $params parameters * @return string with compiled code */ function smarty_modifiercompiler_indent($params, $compiler) { if (!isset($params[1])) { $params[1] = 4; } if (!isset($params[2])) { $params[2] = "' '"; } return 'preg_replace(\'!^!m\',str_repeat(' . $params[2] . ',' . $params[1] . '),' . $params[0] . ')'; } ?>
0x6a
trunk/application/libraries/smarty3/plugins/modifiercompiler.indent.php
PHP
asf20
742
<?php /** * Project: Smarty: the PHP compiling template engine * File: SmartyBC.class.php * SVN: $Id: $ * * 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 2008 New Digital Group, Inc. * @author Monte Ohrt <monte at ohrt dot com> * @author Uwe Tews * @author Rodney Rehm * @package Smarty */ /** * @ignore */ require(dirname(__FILE__) . '/Smarty.class.php'); /** * Smarty Backward Compatability Wrapper Class * * @package Smarty */ class SmartyBC extends Smarty { /** * Smarty 2 BC * @var string */ public $_version = self::SMARTY_VERSION; /** * Initialize new SmartyBC object * * @param array $options options to set during initialization, e.g. array( 'forceCompile' => false ) */ public function __construct(array $options=array()) { parent::__construct($options); // register {php} tag $this->registerPlugin('block', 'php', 'smarty_php_tag'); } /** * wrapper for assign_by_ref * * @param string $tpl_var the template variable name * @param mixed &$value the referenced value to assign */ public function assign_by_ref($tpl_var, &$value) { $this->assignByRef($tpl_var, $value); } /** * wrapper for append_by_ref * * @param string $tpl_var the template variable name * @param mixed &$value the referenced value to append * @param boolean $merge flag if array elements shall be merged */ public function append_by_ref($tpl_var, &$value, $merge = false) { $this->appendByRef($tpl_var, $value, $merge); } /** * clear the given assigned template variable. * * @param string $tpl_var the template variable to clear */ public function clear_assign($tpl_var) { $this->clearAssign($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 * @param bool $cacheable * @param mixed $cache_attrs */ public function register_function($function, $function_impl, $cacheable=true, $cache_attrs=null) { $this->registerPlugin('function', $function, $function_impl, $cacheable, $cache_attrs); } /** * Unregisters custom function * * @param string $function name of template function */ public function unregister_function($function) { $this->unregisterPlugin('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 array $allowed list of allowed methods (empty = all) * @param boolean $smarty_args smarty argument format, else traditional * @param array $block_functs list of methods that are block format */ public function register_object($object, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array()) { settype($allowed, 'array'); settype($smarty_args, 'boolean'); $this->registerObject($object, $object_impl, $allowed, $smarty_args, $block_methods); } /** * Unregisters object * * @param string $object name of template object */ public function unregister_object($object) { $this->unregisterObject($object); } /** * Registers block function to be used in templates * * @param string $block name of template block * @param string $block_impl PHP function to register * @param bool $cacheable * @param mixed $cache_attrs */ public function register_block($block, $block_impl, $cacheable=true, $cache_attrs=null) { $this->registerPlugin('block', $block, $block_impl, $cacheable, $cache_attrs); } /** * Unregisters block function * * @param string $block name of template function */ public function unregister_block($block) { $this->unregisterPlugin('block', $block); } /** * Registers compiler function * * @param string $function name of template function * @param string $function_impl name of PHP function to register * @param bool $cacheable */ public function register_compiler_function($function, $function_impl, $cacheable=true) { $this->registerPlugin('compiler', $function, $function_impl, $cacheable); } /** * Unregisters compiler function * * @param string $function name of template function */ public function unregister_compiler_function($function) { $this->unregisterPlugin('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 */ public function register_modifier($modifier, $modifier_impl) { $this->registerPlugin('modifier', $modifier, $modifier_impl); } /** * Unregisters modifier * * @param string $modifier name of template modifier */ public function unregister_modifier($modifier) { $this->unregisterPlugin('modifier', $modifier); } /** * Registers a resource to fetch a template * * @param string $type name of resource * @param array $functions array of functions to handle resource */ public function register_resource($type, $functions) { $this->registerResource($type, $functions); } /** * Unregisters a resource * * @param string $type name of resource */ public function unregister_resource($type) { $this->unregisterResource($type); } /** * Registers a prefilter function to apply * to a template before compiling * * @param callable $function */ public function register_prefilter($function) { $this->registerFilter('pre', $function); } /** * Unregisters a prefilter function * * @param callable $function */ public function unregister_prefilter($function) { $this->unregisterFilter('pre', $function); } /** * Registers a postfilter function to apply * to a compiled template after compilation * * @param callable $function */ public function register_postfilter($function) { $this->registerFilter('post', $function); } /** * Unregisters a postfilter function * * @param callable $function */ public function unregister_postfilter($function) { $this->unregisterFilter('post', $function); } /** * Registers an output filter function to apply * to a template output * * @param callable $function */ public function register_outputfilter($function) { $this->registerFilter('output', $function); } /** * Unregisters an outputfilter function * * @param callable $function */ public function unregister_outputfilter($function) { $this->unregisterFilter('output', $function); } /** * load a filter of specified type and name * * @param string $type filter type * @param string $name filter name */ public function load_filter($type, $name) { $this->loadFilter($type, $name); } /** * 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 */ public function clear_cache($tpl_file = null, $cache_id = null, $compile_id = null, $exp_time = null) { return $this->clearCache($tpl_file, $cache_id, $compile_id, $exp_time); } /** * clear the entire contents of cache (all templates) * * @param string $exp_time expire time * @return boolean */ public function clear_all_cache($exp_time = null) { return $this->clearCache(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 boolean */ public function is_cached($tpl_file, $cache_id = null, $compile_id = null) { return $this->isCached($tpl_file, $cache_id, $compile_id); } /** * clear all the assigned template variables. */ public function clear_all_assign() { $this->clearAllAssign(); } /** * 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()} */ public function clear_compiled_tpl($tpl_file = null, $compile_id = null, $exp_time = null) { return $this->clearCompiledTemplate($tpl_file, $compile_id, $exp_time); } /** * Checks whether requested template exists. * * @param string $tpl_file * @return boolean */ public function template_exists($tpl_file) { return $this->templateExists($tpl_file); } /** * Returns an array containing template variables * * @param string $name * @return array */ public function get_template_vars($name=null) { return $this->getTemplateVars($name); } /** * Returns an array containing config variables * * @param string $name * @return array */ public function get_config_vars($name=null) { return $this->getConfigVars($name); } /** * load configuration values * * @param string $file * @param string $section * @param string $scope */ public function config_load($file, $section = null, $scope = 'global') { $this->ConfigLoad($file, $section, $scope); } /** * return a reference to a registered object * * @param string $name * @return object */ public function get_registered_object($name) { return $this->getRegisteredObject($name); } /** * clear configuration values * * @param string $var */ public function clear_config($var = null) { $this->clearConfig($var); } /** * trigger Smarty error * * @param string $error_msg * @param integer $error_type */ public function trigger_error($error_msg, $error_type = E_USER_WARNING) { trigger_error("Smarty error: $error_msg", $error_type); } } /** * Smarty {php}{/php} block function * * @param array $params parameter list * @param string $content contents of the block * @param object $template template object * @param boolean &$repeat repeat flag * @return string content re-formatted */ function smarty_php_tag($params, $content, $template, &$repeat) { eval($content); return ''; } ?>
0x6a
trunk/application/libraries/smarty3/SmartyBC.class.php
PHP
asf20
12,903
<?php /** * Project: Smarty: the PHP compiling template engine * File: Smarty.class.php * SVN: $Id: Smarty.class.php 4518 2011-12-18 18:48:07Z rodneyrehm $ * * 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 2008 New Digital Group, Inc. * @author Monte Ohrt <monte at ohrt dot com> * @author Uwe Tews * @author Rodney Rehm * @package Smarty * @version 3.1.7 */ /** * define shorthand directory separator constant */ if (!defined('DS')) { define('DS', DIRECTORY_SEPARATOR); } /** * set SMARTY_DIR to absolute path to Smarty library files. * Sets SMARTY_DIR only if user application has not already defined it. */ if (!defined('SMARTY_DIR')) { define('SMARTY_DIR', dirname(__FILE__) . DS); } /** * set SMARTY_SYSPLUGINS_DIR to absolute path to Smarty internal plugins. * Sets SMARTY_SYSPLUGINS_DIR only if user application has not already defined it. */ if (!defined('SMARTY_SYSPLUGINS_DIR')) { define('SMARTY_SYSPLUGINS_DIR', SMARTY_DIR . 'sysplugins' . DS); } if (!defined('SMARTY_PLUGINS_DIR')) { define('SMARTY_PLUGINS_DIR', SMARTY_DIR . 'plugins' . DS); } if (!defined('SMARTY_MBSTRING')) { define('SMARTY_MBSTRING', function_exists('mb_strlen')); } if (!defined('SMARTY_RESOURCE_CHAR_SET')) { // UTF-8 can only be done properly when mbstring is available! /** * @deprecated in favor of Smarty::$_CHARSET */ define('SMARTY_RESOURCE_CHAR_SET', SMARTY_MBSTRING ? 'UTF-8' : 'ISO-8859-1'); } if (!defined('SMARTY_RESOURCE_DATE_FORMAT')) { /** * @deprecated in favor of Smarty::$_DATE_FORMAT */ define('SMARTY_RESOURCE_DATE_FORMAT', '%b %e, %Y'); } /** * register the class autoloader */ if (!defined('SMARTY_SPL_AUTOLOAD')) { define('SMARTY_SPL_AUTOLOAD', 0); } if (SMARTY_SPL_AUTOLOAD && set_include_path(get_include_path() . PATH_SEPARATOR . SMARTY_SYSPLUGINS_DIR) !== false) { $registeredAutoLoadFunctions = spl_autoload_functions(); if (!isset($registeredAutoLoadFunctions['spl_autoload'])) { spl_autoload_register(); } } else { spl_autoload_register('smartyAutoload'); } /** * Load always needed external class files */ include_once SMARTY_SYSPLUGINS_DIR.'smarty_internal_data.php'; include_once SMARTY_SYSPLUGINS_DIR.'smarty_internal_templatebase.php'; include_once SMARTY_SYSPLUGINS_DIR.'smarty_internal_template.php'; include_once SMARTY_SYSPLUGINS_DIR.'smarty_resource.php'; include_once SMARTY_SYSPLUGINS_DIR.'smarty_internal_resource_file.php'; include_once SMARTY_SYSPLUGINS_DIR.'smarty_cacheresource.php'; include_once SMARTY_SYSPLUGINS_DIR.'smarty_internal_cacheresource_file.php'; /** * This is the main Smarty class * @package Smarty */ class Smarty extends Smarty_Internal_TemplateBase { /**#@+ * constant definitions */ /** * smarty version */ const SMARTY_VERSION = 'Smarty-3.1.7'; /** * define variable scopes */ const SCOPE_LOCAL = 0; const SCOPE_PARENT = 1; const SCOPE_ROOT = 2; const SCOPE_GLOBAL = 3; /** * define caching modes */ const CACHING_OFF = 0; const CACHING_LIFETIME_CURRENT = 1; const CACHING_LIFETIME_SAVED = 2; /** * define compile check modes */ const COMPILECHECK_OFF = 0; const COMPILECHECK_ON = 1; const COMPILECHECK_CACHEMISS = 2; /** * modes for handling of "<?php ... ?>" tags in templates. */ const PHP_PASSTHRU = 0; //-> print tags as plain text const PHP_QUOTE = 1; //-> escape tags as entities const PHP_REMOVE = 2; //-> escape tags as entities const PHP_ALLOW = 3; //-> escape tags as entities /** * filter types */ const FILTER_POST = 'post'; const FILTER_PRE = 'pre'; const FILTER_OUTPUT = 'output'; const FILTER_VARIABLE = 'variable'; /** * plugin types */ const PLUGIN_FUNCTION = 'function'; const PLUGIN_BLOCK = 'block'; const PLUGIN_COMPILER = 'compiler'; const PLUGIN_MODIFIER = 'modifier'; const PLUGIN_MODIFIERCOMPILER = 'modifiercompiler'; /**#@-*/ /** * assigned global tpl vars */ public static $global_tpl_vars = array(); /** * error handler returned by set_error_hanlder() in Smarty::muteExpectedErrors() */ public static $_previous_error_handler = null; /** * contains directories outside of SMARTY_DIR that are to be muted by muteExpectedErrors() */ public static $_muted_directories = array(); /** * Flag denoting if Multibyte String functions are available */ public static $_MBSTRING = SMARTY_MBSTRING; /** * The character set to adhere to (e.g. "UTF-8") */ public static $_CHARSET = SMARTY_RESOURCE_CHAR_SET; /** * The date format to be used internally * (accepts date() and strftime()) */ public static $_DATE_FORMAT = SMARTY_RESOURCE_DATE_FORMAT; /** * Flag denoting if PCRE should run in UTF-8 mode */ public static $_UTF8_MODIFIER = 'u'; /**#@+ * variables */ /** * auto literal on delimiters with whitspace * @var boolean */ public $auto_literal = true; /** * display error on not assigned variables * @var boolean */ public $error_unassigned = false; /** * look up relative filepaths in include_path * @var boolean */ public $use_include_path = false; /** * template directory * @var array */ private $template_dir = array(); /** * joined template directory string used in cache keys * @var string */ public $joined_template_dir = null; /** * joined config directory string used in cache keys * @var string */ public $joined_config_dir = null; /** * default template handler * @var callable */ public $default_template_handler_func = null; /** * default config handler * @var callable */ public $default_config_handler_func = null; /** * default plugin handler * @var callable */ public $default_plugin_handler_func = null; /** * compile directory * @var string */ private $compile_dir = null; /** * plugins directory * @var array */ private $plugins_dir = array(); /** * cache directory * @var string */ private $cache_dir = null; /** * config directory * @var array */ private $config_dir = array(); /** * force template compiling? * @var boolean */ public $force_compile = false; /** * check template for modifications? * @var boolean */ public $compile_check = true; /** * use sub dirs for compiled/cached files? * @var boolean */ public $use_sub_dirs = false; /** * allow ambiguous resources (that are made unique by the resource handler) * @var boolean */ public $allow_ambiguous_resources = false; /** * caching enabled * @var boolean */ public $caching = false; /** * merge compiled includes * @var boolean */ public $merge_compiled_includes = false; /** * cache lifetime in seconds * @var integer */ public $cache_lifetime = 3600; /** * force cache file creation * @var boolean */ public $force_cache = false; /** * Set this if you want different sets of cache files for the same * templates. * * @var string */ public $cache_id = null; /** * Set this if you want different sets of compiled files for the same * templates. * * @var string */ public $compile_id = null; /** * template left-delimiter * @var string */ public $left_delimiter = "{"; /** * template right-delimiter * @var string */ public $right_delimiter = "}"; /**#@+ * security */ /** * class name * * This should be instance of Smarty_Security. * * @var string * @see Smarty_Security */ public $security_class = 'Smarty_Security'; /** * implementation of security class * * @var Smarty_Security */ public $security_policy = null; /** * controls handling of PHP-blocks * * @var integer */ public $php_handling = self::PHP_PASSTHRU; /** * controls if the php template file resource is allowed * * @var bool */ public $allow_php_templates = false; /** * Should compiled-templates be prevented from being called directly? * * {@internal * Currently used by Smarty_Internal_Template only. * }} * * @var boolean */ public $direct_access_security = true; /**#@-*/ /** * debug mode * * Setting this to true enables the debug-console. * * @var boolean */ public $debugging = false; /** * 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> * @var string */ public $debugging_ctrl = 'NONE'; /** * Name of debugging URL-param. * * Only used when $debugging_ctrl is set to 'URL'. * The name of the URL-parameter that activates debugging. * * @var type */ public $smarty_debug_id = 'SMARTY_DEBUG'; /** * Path of debug template. * @var string */ public $debug_tpl = null; /** * When set, smarty uses this value as error_reporting-level. * @var int */ public $error_reporting = null; /** * Internal flag for getTags() * @var boolean */ public $get_used_tags = false; /**#@+ * config var settings */ /** * Controls whether variables with the same name overwrite each other. * @var boolean */ public $config_overwrite = true; /** * Controls whether config values of on/true/yes and off/false/no get converted to boolean. * @var boolean */ public $config_booleanize = true; /** * Controls whether hidden config sections/vars are read from the file. * @var boolean */ public $config_read_hidden = false; /**#@-*/ /**#@+ * resource locking */ /** * locking concurrent compiles * @var boolean */ public $compile_locking = true; /** * Controls whether cache resources should emply locking mechanism * @var boolean */ public $cache_locking = false; /** * seconds to wait for acquiring a lock before ignoring the write lock * @var float */ public $locking_timeout = 10; /**#@-*/ /** * global template functions * @var array */ public $template_functions = array(); /** * resource type used if none given * * Must be an valid key of $registered_resources. * @var string */ public $default_resource_type = 'file'; /** * caching type * * Must be an element of $cache_resource_types. * * @var string */ public $caching_type = 'file'; /** * internal config properties * @var array */ public $properties = array(); /** * config type * @var string */ public $default_config_type = 'file'; /** * cached template objects * @var array */ public $template_objects = array(); /** * check If-Modified-Since headers * @var boolean */ public $cache_modified_check = false; /** * registered plugins * @var array */ public $registered_plugins = array(); /** * plugin search order * @var array */ public $plugin_search_order = array('function', 'block', 'compiler', 'class'); /** * registered objects * @var array */ public $registered_objects = array(); /** * registered classes * @var array */ public $registered_classes = array(); /** * registered filters * @var array */ public $registered_filters = array(); /** * registered resources * @var array */ public $registered_resources = array(); /** * resource handler cache * @var array */ public $_resource_handlers = array(); /** * registered cache resources * @var array */ public $registered_cache_resources = array(); /** * cache resource handler cache * @var array */ public $_cacheresource_handlers = array(); /** * autoload filter * @var array */ public $autoload_filters = array(); /** * default modifier * @var array */ public $default_modifiers = array(); /** * autoescape variable output * @var boolean */ public $escape_html = false; /** * global internal smarty vars * @var array */ public static $_smarty_vars = array(); /** * start time for execution time calculation * @var int */ public $start_time = 0; /** * default file permissions * @var int */ public $_file_perms = 0644; /** * default dir permissions * @var int */ public $_dir_perms = 0771; /** * block tag hierarchy * @var array */ public $_tag_stack = array(); /** * self pointer to Smarty object * @var Smarty */ public $smarty; /** * required by the compiler for BC * @var string */ public $_current_file = null; /** * internal flag to enable parser debugging * @var bool */ public $_parserdebug = false; /** * Saved parameter of merged templates during compilation * * @var array */ public $merged_templates_func = array(); /**#@-*/ /** * Initialize new Smarty object * */ public function __construct() { // selfpointer needed by some other class methods $this->smarty = $this; if (is_callable('mb_internal_encoding')) { mb_internal_encoding(Smarty::$_CHARSET); } $this->start_time = microtime(true); // set default dirs $this->setTemplateDir('.' . DS . 'templates' . DS) ->setCompileDir('.' . DS . 'templates_c' . DS) ->setPluginsDir(SMARTY_PLUGINS_DIR) ->setCacheDir('.' . DS . 'cache' . DS) ->setConfigDir('.' . DS . 'configs' . DS); $this->debug_tpl = 'file:' . dirname(__FILE__) . '/debug.tpl'; if (isset($_SERVER['SCRIPT_NAME'])) { $this->assignGlobal('SCRIPT_NAME', $_SERVER['SCRIPT_NAME']); } } /** * Class destructor */ public function __destruct() { // intentionally left blank } /** * <<magic>> set selfpointer on cloned object */ public function __clone() { $this->smarty = $this; } /** * <<magic>> Generic getter. * * Calls the appropriate getter function. * Issues an E_USER_NOTICE if no valid getter is found. * * @param string $name property name * @return mixed */ public function __get($name) { $allowed = array( 'template_dir' => 'getTemplateDir', 'config_dir' => 'getConfigDir', 'plugins_dir' => 'getPluginsDir', 'compile_dir' => 'getCompileDir', 'cache_dir' => 'getCacheDir', ); if (isset($allowed[$name])) { return $this->{$allowed[$name]}(); } else { trigger_error('Undefined property: '. get_class($this) .'::$'. $name, E_USER_NOTICE); } } /** * <<magic>> Generic setter. * * Calls the appropriate setter function. * Issues an E_USER_NOTICE if no valid setter is found. * * @param string $name property name * @param mixed $value parameter passed to setter */ public function __set($name, $value) { $allowed = array( 'template_dir' => 'setTemplateDir', 'config_dir' => 'setConfigDir', 'plugins_dir' => 'setPluginsDir', 'compile_dir' => 'setCompileDir', 'cache_dir' => 'setCacheDir', ); if (isset($allowed[$name])) { $this->{$allowed[$name]}($value); } else { trigger_error('Undefined property: ' . get_class($this) . '::$' . $name, E_USER_NOTICE); } } /** * Check if a template resource exists * * @param string $resource_name template name * @return boolean status */ public function templateExists($resource_name) { // create template object $save = $this->template_objects; $tpl = new $this->template_class($resource_name, $this); // check if it does exists $result = $tpl->source->exists; $this->template_objects = $save; return $result; } /** * Returns a single or all global variables * * @param object $smarty * @param string $varname variable name or null * @return string variable value or or array of variables */ public function getGlobal($varname = null) { if (isset($varname)) { if (isset(self::$global_tpl_vars[$varname])) { return self::$global_tpl_vars[$varname]->value; } else { return ''; } } else { $_result = array(); foreach (self::$global_tpl_vars AS $key => $var) { $_result[$key] = $var->value; } return $_result; } } /** * Empty cache folder * * @param integer $exp_time expiration time * @param string $type resource type * @return integer number of cache files deleted */ function clearAllCache($exp_time = null, $type = null) { // load cache resource and call clearAll $_cache_resource = Smarty_CacheResource::load($this, $type); Smarty_CacheResource::invalidLoadedCache($this); return $_cache_resource->clearAll($this, $exp_time); } /** * Empty cache for a specific template * * @param string $template_name template name * @param string $cache_id cache id * @param string $compile_id compile id * @param integer $exp_time expiration time * @param string $type resource type * @return integer number of cache files deleted */ public function clearCache($template_name, $cache_id = null, $compile_id = null, $exp_time = null, $type = null) { // load cache resource and call clear $_cache_resource = Smarty_CacheResource::load($this, $type); Smarty_CacheResource::invalidLoadedCache($this); return $_cache_resource->clear($this, $template_name, $cache_id, $compile_id, $exp_time); } /** * Loads security class and enables security * * @param string|Smarty_Security $security_class if a string is used, it must be class-name * @return Smarty current Smarty instance for chaining * @throws SmartyException when an invalid class name is provided */ public function enableSecurity($security_class = null) { if ($security_class instanceof Smarty_Security) { $this->security_policy = $security_class; return $this; } elseif (is_object($security_class)) { throw new SmartyException("Class '" . get_class($security_class) . "' must extend Smarty_Security."); } if ($security_class == null) { $security_class = $this->security_class; } if (!class_exists($security_class)) { throw new SmartyException("Security class '$security_class' is not defined"); } elseif ($security_class !== 'Smarty_Security' && !is_subclass_of($security_class, 'Smarty_Security')) { throw new SmartyException("Class '$security_class' must extend Smarty_Security."); } else { $this->security_policy = new $security_class($this); } return $this; } /** * Disable security * @return Smarty current Smarty instance for chaining */ public function disableSecurity() { $this->security_policy = null; return $this; } /** * Set template directory * * @param string|array $template_dir directory(s) of template sources * @return Smarty current Smarty instance for chaining */ public function setTemplateDir($template_dir) { $this->template_dir = array(); foreach ((array) $template_dir as $k => $v) { $this->template_dir[$k] = rtrim($v, '/\\') . DS; } $this->joined_template_dir = join(DIRECTORY_SEPARATOR, $this->template_dir); return $this; } /** * Add template directory(s) * * @param string|array $template_dir directory(s) of template sources * @param string $key of the array element to assign the template dir to * @return Smarty current Smarty instance for chaining * @throws SmartyException when the given template directory is not valid */ public function addTemplateDir($template_dir, $key=null) { // make sure we're dealing with an array $this->template_dir = (array) $this->template_dir; if (is_array($template_dir)) { foreach ($template_dir as $k => $v) { if (is_int($k)) { // indexes are not merged but appended $this->template_dir[] = rtrim($v, '/\\') . DS; } else { // string indexes are overridden $this->template_dir[$k] = rtrim($v, '/\\') . DS; } } } elseif ($key !== null) { // override directory at specified index $this->template_dir[$key] = rtrim($template_dir, '/\\') . DS; } else { // append new directory $this->template_dir[] = rtrim($template_dir, '/\\') . DS; } $this->joined_template_dir = join(DIRECTORY_SEPARATOR, $this->template_dir); return $this; } /** * Get template directories * * @param mixed index of directory to get, null to get all * @return array|string list of template directories, or directory of $index */ public function getTemplateDir($index=null) { if ($index !== null) { return isset($this->template_dir[$index]) ? $this->template_dir[$index] : null; } return (array)$this->template_dir; } /** * Set config directory * * @param string|array $template_dir directory(s) of configuration sources * @return Smarty current Smarty instance for chaining */ public function setConfigDir($config_dir) { $this->config_dir = array(); foreach ((array) $config_dir as $k => $v) { $this->config_dir[$k] = rtrim($v, '/\\') . DS; } $this->joined_config_dir = join(DIRECTORY_SEPARATOR, $this->config_dir); return $this; } /** * Add config directory(s) * * @param string|array $config_dir directory(s) of config sources * @param string key of the array element to assign the config dir to * @return Smarty current Smarty instance for chaining */ public function addConfigDir($config_dir, $key=null) { // make sure we're dealing with an array $this->config_dir = (array) $this->config_dir; if (is_array($config_dir)) { foreach ($config_dir as $k => $v) { if (is_int($k)) { // indexes are not merged but appended $this->config_dir[] = rtrim($v, '/\\') . DS; } else { // string indexes are overridden $this->config_dir[$k] = rtrim($v, '/\\') . DS; } } } elseif( $key !== null ) { // override directory at specified index $this->config_dir[$key] = rtrim($config_dir, '/\\') . DS; } else { // append new directory $this->config_dir[] = rtrim($config_dir, '/\\') . DS; } $this->joined_config_dir = join(DIRECTORY_SEPARATOR, $this->config_dir); return $this; } /** * Get config directory * * @param mixed index of directory to get, null to get all * @return array|string configuration directory */ public function getConfigDir($index=null) { if ($index !== null) { return isset($this->config_dir[$index]) ? $this->config_dir[$index] : null; } return (array)$this->config_dir; } /** * Set plugins directory * * @param string|array $plugins_dir directory(s) of plugins * @return Smarty current Smarty instance for chaining */ public function setPluginsDir($plugins_dir) { $this->plugins_dir = array(); foreach ((array)$plugins_dir as $k => $v) { $this->plugins_dir[$k] = rtrim($v, '/\\') . DS; } return $this; } /** * Adds directory of plugin files * * @param object $smarty * @param string $ |array $ plugins folder * @return Smarty current Smarty instance for chaining */ public function addPluginsDir($plugins_dir) { // make sure we're dealing with an array $this->plugins_dir = (array) $this->plugins_dir; if (is_array($plugins_dir)) { foreach ($plugins_dir as $k => $v) { if (is_int($k)) { // indexes are not merged but appended $this->plugins_dir[] = rtrim($v, '/\\') . DS; } else { // string indexes are overridden $this->plugins_dir[$k] = rtrim($v, '/\\') . DS; } } } else { // append new directory $this->plugins_dir[] = rtrim($plugins_dir, '/\\') . DS; } $this->plugins_dir = array_unique($this->plugins_dir); return $this; } /** * Get plugin directories * * @return array list of plugin directories */ public function getPluginsDir() { return (array)$this->plugins_dir; } /** * Set compile directory * * @param string $compile_dir directory to store compiled templates in * @return Smarty current Smarty instance for chaining */ public function setCompileDir($compile_dir) { $this->compile_dir = rtrim($compile_dir, '/\\') . DS; if (!isset(Smarty::$_muted_directories[$this->compile_dir])) { Smarty::$_muted_directories[$this->compile_dir] = null; } return $this; } /** * Get compiled directory * * @return string path to compiled templates */ public function getCompileDir() { return $this->compile_dir; } /** * Set cache directory * * @param string $cache_dir directory to store cached templates in * @return Smarty current Smarty instance for chaining */ public function setCacheDir($cache_dir) { $this->cache_dir = rtrim($cache_dir, '/\\') . DS; if (!isset(Smarty::$_muted_directories[$this->cache_dir])) { Smarty::$_muted_directories[$this->cache_dir] = null; } return $this; } /** * Get cache directory * * @return string path of cache directory */ public function getCacheDir() { return $this->cache_dir; } /** * Set default modifiers * * @param array|string $modifiers modifier or list of modifiers to set * @return Smarty current Smarty instance for chaining */ public function setDefaultModifiers($modifiers) { $this->default_modifiers = (array) $modifiers; return $this; } /** * Add default modifiers * * @param array|string $modifiers modifier or list of modifiers to add * @return Smarty current Smarty instance for chaining */ public function addDefaultModifiers($modifiers) { if (is_array($modifiers)) { $this->default_modifiers = array_merge($this->default_modifiers, $modifiers); } else { $this->default_modifiers[] = $modifiers; } return $this; } /** * Get default modifiers * * @return array list of default modifiers */ public function getDefaultModifiers() { return $this->default_modifiers; } /** * Set autoload filters * * @param array $filters filters to load automatically * @param string $type "pre", "output", … specify the filter type to set. Defaults to none treating $filters' keys as the appropriate types * @return Smarty current Smarty instance for chaining */ public function setAutoloadFilters($filters, $type=null) { if ($type !== null) { $this->autoload_filters[$type] = (array) $filters; } else { $this->autoload_filters = (array) $filters; } return $this; } /** * Add autoload filters * * @param array $filters filters to load automatically * @param string $type "pre", "output", … specify the filter type to set. Defaults to none treating $filters' keys as the appropriate types * @return Smarty current Smarty instance for chaining */ public function addAutoloadFilters($filters, $type=null) { if ($type !== null) { if (!empty($this->autoload_filters[$type])) { $this->autoload_filters[$type] = array_merge($this->autoload_filters[$type], (array) $filters); } else { $this->autoload_filters[$type] = (array) $filters; } } else { foreach ((array) $filters as $key => $value) { if (!empty($this->autoload_filters[$key])) { $this->autoload_filters[$key] = array_merge($this->autoload_filters[$key], (array) $value); } else { $this->autoload_filters[$key] = (array) $value; } } } return $this; } /** * Get autoload filters * * @param string $type type of filter to get autoloads for. Defaults to all autoload filters * @return array array( 'type1' => array( 'filter1', 'filter2', … ) ) or array( 'filter1', 'filter2', …) if $type was specified */ public function getAutoloadFilters($type=null) { if ($type !== null) { return isset($this->autoload_filters[$type]) ? $this->autoload_filters[$type] : array(); } return $this->autoload_filters; } /** * return name of debugging template * * @return string */ public function getDebugTemplate() { return $this->debug_tpl; } /** * set the debug template * * @param string $tpl_name * @return Smarty current Smarty instance for chaining * @throws SmartyException if file is not readable */ public function setDebugTemplate($tpl_name) { if (!is_readable($tpl_name)) { throw new SmartyException("Unknown file '{$tpl_name}'"); } $this->debug_tpl = $tpl_name; return $this; } /** * creates a template object * * @param string $template the resource handle of the template file * @param mixed $cache_id cache id to be used with this template * @param mixed $compile_id compile id to be used with this template * @param object $parent next higher level of Smarty variables * @param boolean $do_clone flag is Smarty object shall be cloned * @return object template object */ public function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null, $do_clone = true) { if (!empty($cache_id) && (is_object($cache_id) || is_array($cache_id))) { $parent = $cache_id; $cache_id = null; } if (!empty($parent) && is_array($parent)) { $data = $parent; $parent = null; } else { $data = null; } // default to cache_id and compile_id of Smarty object $cache_id = $cache_id === null ? $this->cache_id : $cache_id; $compile_id = $compile_id === null ? $this->compile_id : $compile_id; // already in template cache? if ($this->allow_ambiguous_resources) { $_templateId = Smarty_Resource::getUniqueTemplateName($this, $template) . $cache_id . $compile_id; } else { $_templateId = $this->joined_template_dir . '#' . $template . $cache_id . $compile_id; } if (isset($_templateId[150])) { $_templateId = sha1($_templateId); } if ($do_clone) { if (isset($this->template_objects[$_templateId])) { // return cached template object $tpl = clone $this->template_objects[$_templateId]; $tpl->smarty = clone $tpl->smarty; $tpl->parent = $parent; $tpl->tpl_vars = array(); $tpl->config_vars = array(); } else { $tpl = new $this->template_class($template, clone $this, $parent, $cache_id, $compile_id); } } else { if (isset($this->template_objects[$_templateId])) { // return cached template object $tpl = $this->template_objects[$_templateId]; $tpl->parent = $parent; $tpl->tpl_vars = array(); $tpl->config_vars = array(); } else { $tpl = new $this->template_class($template, $this, $parent, $cache_id, $compile_id); } } // fill data if present if (!empty($data) && is_array($data)) { // set up variable values foreach ($data as $_key => $_val) { $tpl->tpl_vars[$_key] = new Smarty_variable($_val); } } return $tpl; } /** * Takes unknown classes and loads plugin files for them * class name format: Smarty_PluginType_PluginName * plugin filename format: plugintype.pluginname.php * * @param string $plugin_name class plugin name to load * @param bool $check check if already loaded * @return string |boolean filepath of loaded file or false */ public function loadPlugin($plugin_name, $check = true) { // if function or class exists, exit silently (already loaded) if ($check && (is_callable($plugin_name) || class_exists($plugin_name, false))) { return true; } // Plugin name is expected to be: Smarty_[Type]_[Name] $_name_parts = explode('_', $plugin_name, 3); // class name must have three parts to be valid plugin // count($_name_parts) < 3 === !isset($_name_parts[2]) if (!isset($_name_parts[2]) || strtolower($_name_parts[0]) !== 'smarty') { throw new SmartyException("plugin {$plugin_name} is not a valid name format"); return false; } // if type is "internal", get plugin from sysplugins if (strtolower($_name_parts[1]) == 'internal') { $file = SMARTY_SYSPLUGINS_DIR . strtolower($plugin_name) . '.php'; if (file_exists($file)) { require_once($file); return $file; } else { return false; } } // plugin filename is expected to be: [type].[name].php $_plugin_filename = "{$_name_parts[1]}.{$_name_parts[2]}.php"; // loop through plugin dirs and find the plugin foreach($this->getPluginsDir() as $_plugin_dir) { $names = array( $_plugin_dir . $_plugin_filename, $_plugin_dir . strtolower($_plugin_filename), ); foreach ($names as $file) { if (file_exists($file)) { require_once($file); return $file; } if ($this->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_plugin_dir)) { // try PHP include_path if (($file = Smarty_Internal_Get_Include_Path::getIncludePath($file)) !== false) { require_once($file); return $file; } } } } // no plugin loaded return false; } /** * Compile all template files * * @param string $extension file extension * @param bool $force_compile force all to recompile * @param int $time_limit * @param int $max_errors * @return integer number of template files recompiled */ public function compileAllTemplates($extention = '.tpl', $force_compile = false, $time_limit = 0, $max_errors = null) { return Smarty_Internal_Utility::compileAllTemplates($extention, $force_compile, $time_limit, $max_errors, $this); } /** * Compile all config files * * @param string $extension file extension * @param bool $force_compile force all to recompile * @param int $time_limit * @param int $max_errors * @return integer number of template files recompiled */ public function compileAllConfig($extention = '.conf', $force_compile = false, $time_limit = 0, $max_errors = null) { return Smarty_Internal_Utility::compileAllConfig($extention, $force_compile, $time_limit, $max_errors, $this); } /** * Delete compiled template file * * @param string $resource_name template name * @param string $compile_id compile id * @param integer $exp_time expiration time * @return integer number of template files deleted */ public function clearCompiledTemplate($resource_name = null, $compile_id = null, $exp_time = null) { return Smarty_Internal_Utility::clearCompiledTemplate($resource_name, $compile_id, $exp_time, $this); } /** * Return array of tag/attributes of all tags used by an template * * @param object $templae template object * @return array of tag/attributes */ public function getTags(Smarty_Internal_Template $template) { return Smarty_Internal_Utility::getTags($template); } /** * Run installation test * * @param array $errors Array to write errors into, rather than outputting them * @return boolean true if setup is fine, false if something is wrong */ public function testInstall(&$errors=null) { return Smarty_Internal_Utility::testInstall($this, $errors); } /** * Error Handler to mute expected messages * * @link http://php.net/set_error_handler * @param integer $errno Error level * @return boolean */ public static function mutingErrorHandler($errno, $errstr, $errfile, $errline, $errcontext) { $_is_muted_directory = false; // add the SMARTY_DIR to the list of muted directories if (!isset(Smarty::$_muted_directories[SMARTY_DIR])) { $smarty_dir = realpath(SMARTY_DIR); Smarty::$_muted_directories[SMARTY_DIR] = array( 'file' => $smarty_dir, 'length' => strlen($smarty_dir), ); } // walk the muted directories and test against $errfile foreach (Smarty::$_muted_directories as $key => &$dir) { if (!$dir) { // resolve directory and length for speedy comparisons $file = realpath($key); $dir = array( 'file' => $file, 'length' => strlen($file), ); } if (!strncmp($errfile, $dir['file'], $dir['length'])) { $_is_muted_directory = true; break; } } // pass to next error handler if this error did not occur inside SMARTY_DIR // or the error was within smarty but masked to be ignored if (!$_is_muted_directory || ($errno && $errno & error_reporting())) { if (Smarty::$_previous_error_handler) { return call_user_func(Smarty::$_previous_error_handler, $errno, $errstr, $errfile, $errline, $errcontext); } else { return false; } } } /** * Enable error handler to mute expected messages * * @return void */ public static function muteExpectedErrors() { /* error muting is done because some people implemented custom error_handlers using http://php.net/set_error_handler and for some reason did not understand the following paragraph: It is important to remember that the standard PHP error handler is completely bypassed for the error types specified by error_types unless the callback function returns FALSE. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator. Smarty deliberately uses @filemtime() over file_exists() and filemtime() in some places. Reasons include - @filemtime() is almost twice as fast as using an additional file_exists() - between file_exists() and filemtime() a possible race condition is opened, which does not exist using the simple @filemtime() approach. */ $error_handler = array('Smarty', 'mutingErrorHandler'); $previous = set_error_handler($error_handler); // avoid dead loops if ($previous !== $error_handler) { Smarty::$_previous_error_handler = $previous; } } /** * Disable error handler muting expected messages * * @return void */ public static function unmuteExpectedErrors() { restore_error_handler(); } } // let PCRE (preg_*) treat strings as ISO-8859-1 if we're not dealing with UTF-8 if (Smarty::$_CHARSET !== 'UTF-8') { Smarty::$_UTF8_MODIFIER = ''; } /** * Smarty exception class * @package Smarty */ class SmartyException extends Exception { } /** * Smarty compiler exception class * @package Smarty */ class SmartyCompilerException extends SmartyException { } /** * Autoloader */ function smartyAutoload($class) { $_class = strtolower($class); $_classes = array( 'smarty_config_source' => true, 'smarty_config_compiled' => true, 'smarty_security' => true, 'smarty_cacheresource' => true, 'smarty_cacheresource_custom' => true, 'smarty_cacheresource_keyvaluestore' => true, 'smarty_resource' => true, 'smarty_resource_custom' => true, 'smarty_resource_uncompiled' => true, 'smarty_resource_recompiled' => true, ); if (!strncmp($_class, 'smarty_internal_', 16) || isset($_classes[$_class])) { include SMARTY_SYSPLUGINS_DIR . $_class . '.php'; } } ?>
0x6a
trunk/application/libraries/smarty3/Smarty.class.php
PHP
asf20
46,293
{capture name='_smarty_debug' assign=debug_output} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Smarty Debug Console</title> <style type="text/css"> {literal} body, h1, h2, td, th, p { font-family: sans-serif; font-weight: normal; font-size: 0.9em; margin: 1px; padding: 0; } h1 { margin: 0; text-align: left; padding: 2px; background-color: #f0c040; color: black; font-weight: bold; font-size: 1.2em; } h2 { background-color: #9B410E; color: white; text-align: left; font-weight: bold; padding: 2px; border-top: 1px solid black; } body { background: black; } p, table, div { background: #f0ead8; } p { margin: 0; font-style: italic; text-align: center; } table { width: 100%; } th, td { font-family: monospace; vertical-align: top; text-align: left; width: 50%; } td { color: green; } .odd { background-color: #eeeeee; } .even { background-color: #fafafa; } .exectime { font-size: 0.8em; font-style: italic; } #table_assigned_vars th { color: blue; } #table_config_vars th { color: maroon; } {/literal} </style> </head> <body> <h1>Smarty Debug Console - {if isset($template_name)}{$template_name|debug_print_var nofilter}{else}Total Time {$execution_time|string_format:"%.5f"}{/if}</h1> {if !empty($template_data)} <h2>included templates &amp; config files (load time in seconds)</h2> <div> {foreach $template_data as $template} <font color=brown>{$template.name}</font> <span class="exectime"> (compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"}) </span> <br> {/foreach} </div> {/if} <h2>assigned template variables</h2> <table id="table_assigned_vars"> {foreach $assigned_vars as $vars} <tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}"> <th>${$vars@key|escape:'html'}</th> <td>{$vars|debug_print_var nofilter}</td></tr> {/foreach} </table> <h2>assigned config file variables (outer template scope)</h2> <table id="table_config_vars"> {foreach $config_vars as $vars} <tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}"> <th>{$vars@key|escape:'html'}</th> <td>{$vars|debug_print_var nofilter}</td></tr> {/foreach} </table> </body> </html> {/capture} <script type="text/javascript"> {$id = $template_name|default:''|md5} _smarty_console = window.open("","console{$id}","width=680,height=600,resizable,scrollbars=yes"); _smarty_console.document.write("{$debug_output|escape:'javascript' nofilter}"); _smarty_console.document.close(); </script>
0x6a
trunk/application/libraries/smarty3/debug.tpl
Smarty
asf20
2,863
<?php /** * Smarty Internal Plugin Debug * * Class to collect data for the Smarty Debugging Consol * * @package Smarty * @subpackage Debug * @author Uwe Tews */ /** * Smarty Internal Plugin Debug Class * * @package Smarty * @subpackage Debug */ class Smarty_Internal_Debug extends Smarty_Internal_Data { /** * template data * * @var array */ public static $template_data = array(); /** * Start logging of compile time * * @param object $template */ public static function start_compile($template) { $key = self::get_key($template); self::$template_data[$key]['start_time'] = microtime(true); } /** * End logging of compile time * * @param object $template */ public static function end_compile($template) { $key = self::get_key($template); self::$template_data[$key]['compile_time'] += microtime(true) - self::$template_data[$key]['start_time']; } /** * Start logging of render time * * @param object $template */ public static function start_render($template) { $key = self::get_key($template); self::$template_data[$key]['start_time'] = microtime(true); } /** * End logging of compile time * * @param object $template */ public static function end_render($template) { $key = self::get_key($template); self::$template_data[$key]['render_time'] += microtime(true) - self::$template_data[$key]['start_time']; } /** * Start logging of cache time * * @param object $template cached template */ public static function start_cache($template) { $key = self::get_key($template); self::$template_data[$key]['start_time'] = microtime(true); } /** * End logging of cache time * * @param object $template cached template */ public static function end_cache($template) { $key = self::get_key($template); self::$template_data[$key]['cache_time'] += microtime(true) - self::$template_data[$key]['start_time']; } /** * Opens a window for the Smarty Debugging Consol and display the data * * @param Smarty_Internal_Template|Smarty $obj object to debug */ public static function display_debug($obj) { // prepare information of assigned variables $ptr = self::get_debug_vars($obj); if ($obj instanceof Smarty) { $smarty = clone $obj; } else { $smarty = clone $obj->smarty; } $_assigned_vars = $ptr->tpl_vars; ksort($_assigned_vars); $_config_vars = $ptr->config_vars; ksort($_config_vars); $smarty->registered_filters = array(); $smarty->autoload_filters = array(); $smarty->default_modifiers = array(); $smarty->force_compile = false; $smarty->left_delimiter = '{'; $smarty->right_delimiter = '}'; $smarty->debugging = false; $smarty->force_compile = false; $_template = new Smarty_Internal_Template($smarty->debug_tpl, $smarty); $_template->caching = false; $_template->disableSecurity(); $_template->cache_id = null; $_template->compile_id = null; if ($obj instanceof Smarty_Internal_Template) { $_template->assign('template_name', $obj->source->type . ':' . $obj->source->name); } if ($obj instanceof Smarty) { $_template->assign('template_data', self::$template_data); } else { $_template->assign('template_data', null); } $_template->assign('assigned_vars', $_assigned_vars); $_template->assign('config_vars', $_config_vars); $_template->assign('execution_time', microtime(true) - $smarty->start_time); echo $_template->fetch(); } /** * Recursively gets variables from all template/data scopes * * @param Smarty_Internal_Template|Smarty_Data $obj object to debug * @return StdClass */ public static function get_debug_vars($obj) { $config_vars = $obj->config_vars; $tpl_vars = array(); foreach ($obj->tpl_vars as $key => $var) { $tpl_vars[$key] = clone $var; if ($obj instanceof Smarty_Internal_Template) { $tpl_vars[$key]->scope = $obj->source->type . ':' . $obj->source->name; } elseif ($obj instanceof Smarty_Data) { $tpl_vars[$key]->scope = 'Data object'; } else { $tpl_vars[$key]->scope = 'Smarty root'; } } if (isset($obj->parent)) { $parent = self::get_debug_vars($obj->parent); $tpl_vars = array_merge($parent->tpl_vars, $tpl_vars); $config_vars = array_merge($parent->config_vars, $config_vars); } else { foreach (Smarty::$global_tpl_vars as $name => $var) { if (!array_key_exists($name, $tpl_vars)) { $clone = clone $var; $clone->scope = 'Global'; $tpl_vars[$name] = $clone; } } } return (object) array('tpl_vars' => $tpl_vars, 'config_vars' => $config_vars); } /** * Return key into $template_data for template * * @param object $template template object * @return string key into $template_data */ private static function get_key($template) { static $_is_stringy = array('string' => true, 'eval' => true); // calculate Uid if not already done if ($template->source->uid == '') { $template->source->filepath; } $key = $template->source->uid; if (isset(self::$template_data[$key])) { return $key; } else { if (isset($_is_stringy[$template->source->type])) { self::$template_data[$key]['name'] = '\''.substr($template->source->name,0,25).'...\''; } else { self::$template_data[$key]['name'] = $template->source->filepath; } self::$template_data[$key]['compile_time'] = 0; self::$template_data[$key]['render_time'] = 0; self::$template_data[$key]['cache_time'] = 0; return $key; } } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_internal_debug.php
PHP
asf20
6,612
<?php /** * Smarty Internal Plugin Compile Modifier * * Compiles code for modifier execution * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Modifier Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Private_Modifier extends Smarty_Internal_CompileBase { /** * Compiles code for modifier execution * * @param array $args array with attributes from parser * @param object $compiler compiler object * @param array $parameter array with compilation parameter * @return string compiled code */ public function compile($args, $compiler, $parameter) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); $output = $parameter['value']; // loop over list of modifiers foreach ($parameter['modifierlist'] as $single_modifier) { $modifier = $single_modifier[0]; $single_modifier[0] = $output; $params = implode(',', $single_modifier); // check for registered modifier if (isset($compiler->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER][$modifier])) { $function = $compiler->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER][$modifier][0]; if (!is_array($function)) { $output = "{$function}({$params})"; } else { if (is_object($function[0])) { $output = '$_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER][\'' . $modifier . '\'][0][0]->' . $function[1] . '(' . $params . ')'; } else { $output = $function[0] . '::' . $function[1] . '(' . $params . ')'; } } } else if (isset($compiler->smarty->registered_plugins[Smarty::PLUGIN_MODIFIERCOMPILER][$modifier][0])) { $output = call_user_func($compiler->smarty->registered_plugins[Smarty::PLUGIN_MODIFIERCOMPILER][$modifier][0], $single_modifier, $compiler->smarty); // check for plugin modifiercompiler } else if ($compiler->smarty->loadPlugin('smarty_modifiercompiler_' . $modifier)) { // check if modifier allowed if (!is_object($compiler->smarty->security_policy) || $compiler->smarty->security_policy->isTrustedModifier($modifier, $compiler)) { $plugin = 'smarty_modifiercompiler_' . $modifier; $output = $plugin($single_modifier, $compiler); } // check for plugin modifier } else if ($function = $compiler->getPlugin($modifier, Smarty::PLUGIN_MODIFIER)) { // check if modifier allowed if (!is_object($compiler->smarty->security_policy) || $compiler->smarty->security_policy->isTrustedModifier($modifier, $compiler)) { $output = "{$function}({$params})"; } // check if trusted PHP function } else if (is_callable($modifier)) { // check if modifier allowed if (!is_object($compiler->smarty->security_policy) || $compiler->smarty->security_policy->isTrustedPhpModifier($modifier, $compiler)) { $output = "{$modifier}({$params})"; } } else { $compiler->trigger_template_error("unknown modifier \"" . $modifier . "\"", $compiler->lex->taglineno); } } return $output; } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_internal_compile_private_modifier.php
PHP
asf20
3,682
<?php /** * Smarty Internal Plugin Compile Rdelim * * Compiles the {rdelim} tag * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Rdelim Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Rdelim extends Smarty_Internal_CompileBase { /** * Compiles code for the {rdelim} tag * * This tag does output the right delimiter. * * @param array $args array with attributes from parser * @param object $compiler compiler object * @return string compiled code */ public function compile($args, $compiler) { $_attr = $this->getAttributes($compiler, $args); if ($_attr['nocache'] === true) { $compiler->trigger_template_error('nocache option not allowed', $compiler->lex->taglineno); } // this tag does not return compiled code $compiler->has_code = true; return $compiler->smarty->right_delimiter; } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_internal_compile_rdelim.php
PHP
asf20
1,051
<?php /** * Smarty Internal Plugin Smarty Template Base * * This file contains the basic shared methodes for template handling * * @package Smarty * @subpackage Template * @author Uwe Tews */ /** * Class with shared template methodes * * @package Smarty * @subpackage Template */ abstract class Smarty_Internal_TemplateBase extends Smarty_Internal_Data { /** * fetches a rendered Smarty template * * @param string $template the resource handle of the template file or template object * @param mixed $cache_id cache id to be used with this template * @param mixed $compile_id compile id to be used with this template * @param object $parent next higher level of Smarty variables * @param bool $display true: display, false: fetch * @param bool $merge_tpl_vars if true parent template variables merged in to local scope * @param bool $no_output_filter if true do not run output filter * @return string rendered template output */ public function fetch($template = null, $cache_id = null, $compile_id = null, $parent = null, $display = false, $merge_tpl_vars = true, $no_output_filter = false) { if ($template === null && $this instanceof $this->template_class) { $template = $this; } if (!empty($cache_id) && is_object($cache_id)) { $parent = $cache_id; $cache_id = null; } if ($parent === null && ($this instanceof Smarty || is_string($template))) { $parent = $this; } // create template object if necessary $_template = ($template instanceof $this->template_class) ? $template : $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false); // if called by Smarty object make sure we use current caching status if ($this instanceof Smarty) { $_template->caching = $this->caching; } // merge all variable scopes into template if ($merge_tpl_vars) { // save local variables $save_tpl_vars = $_template->tpl_vars; $save_config_vars = $_template->config_vars; $ptr_array = array($_template); $ptr = $_template; while (isset($ptr->parent)) { $ptr_array[] = $ptr = $ptr->parent; } $ptr_array = array_reverse($ptr_array); $parent_ptr = reset($ptr_array); $tpl_vars = $parent_ptr->tpl_vars; $config_vars = $parent_ptr->config_vars; while ($parent_ptr = next($ptr_array)) { if (!empty($parent_ptr->tpl_vars)) { $tpl_vars = array_merge($tpl_vars, $parent_ptr->tpl_vars); } if (!empty($parent_ptr->config_vars)) { $config_vars = array_merge($config_vars, $parent_ptr->config_vars); } } if (!empty(Smarty::$global_tpl_vars)) { $tpl_vars = array_merge(Smarty::$global_tpl_vars, $tpl_vars); } $_template->tpl_vars = $tpl_vars; $_template->config_vars = $config_vars; } // dummy local smarty variable if (!isset($_template->tpl_vars['smarty'])) { $_template->tpl_vars['smarty'] = new Smarty_Variable; } if (isset($this->smarty->error_reporting)) { $_smarty_old_error_level = error_reporting($this->smarty->error_reporting); } // check URL debugging control if (!$this->smarty->debugging && $this->smarty->debugging_ctrl == 'URL') { if (isset($_SERVER['QUERY_STRING'])) { $_query_string = $_SERVER['QUERY_STRING']; } else { $_query_string = ''; } if (false !== strpos($_query_string, $this->smarty->smarty_debug_id)) { if (false !== strpos($_query_string, $this->smarty->smarty_debug_id . '=on')) { // enable debugging for this browser session setcookie('SMARTY_DEBUG', true); $this->smarty->debugging = true; } elseif (false !== strpos($_query_string, $this->smarty->smarty_debug_id . '=off')) { // disable debugging for this browser session setcookie('SMARTY_DEBUG', false); $this->smarty->debugging = false; } else { // enable debugging for this page $this->smarty->debugging = true; } } else { if (isset($_COOKIE['SMARTY_DEBUG'])) { $this->smarty->debugging = true; } } } // must reset merge template date $_template->smarty->merged_templates_func = array(); // get rendered template // disable caching for evaluated code if ($_template->source->recompiled) { $_template->caching = false; } // checks if template exists if (!$_template->source->exists) { if ($_template->parent instanceof Smarty_Internal_Template) { $parent_resource = " in '{$_template->parent->template_resource}'"; } else { $parent_resource = ''; } throw new SmartyException("Unable to load template {$_template->source->type} '{$_template->source->name}'{$parent_resource}"); } // read from cache or render if (!($_template->caching == Smarty::CACHING_LIFETIME_CURRENT || $_template->caching == Smarty::CACHING_LIFETIME_SAVED) || !$_template->cached->valid) { // render template (not loaded and not in cache) if (!$_template->source->uncompiled) { $_smarty_tpl = $_template; if ($_template->source->recompiled) { if ($this->smarty->debugging) { Smarty_Internal_Debug::start_compile($_template); } $code = $_template->compiler->compileTemplate($_template); if ($this->smarty->debugging) { Smarty_Internal_Debug::end_compile($_template); } if ($this->smarty->debugging) { Smarty_Internal_Debug::start_render($_template); } try { ob_start(); eval("?>" . $code); unset($code); } catch (Exception $e) { ob_get_clean(); throw $e; } } else { if (!$_template->compiled->exists || ($_template->smarty->force_compile && !$_template->compiled->isCompiled)) { $_template->compileTemplateSource(); } if ($this->smarty->debugging) { Smarty_Internal_Debug::start_render($_template); } if (!$_template->compiled->loaded) { include($_template->compiled->filepath); if ($_template->mustCompile) { // recompile and load again $_template->compileTemplateSource(); include($_template->compiled->filepath); } $_template->compiled->loaded = true; } else { $_template->decodeProperties($_template->compiled->_properties, false); } try { ob_start(); if (empty($_template->properties['unifunc']) || !is_callable($_template->properties['unifunc'])) { throw new SmartyException("Invalid compiled template for '{$_template->template_resource}'"); } array_unshift($_template->_capture_stack,array()); // // render compiled template // $_template->properties['unifunc']($_template); // any unclosed {capture} tags ? if (isset($_template->_capture_stack[0][0])) { $_template->capture_error(); } array_shift($_template->_capture_stack); } catch (Exception $e) { ob_get_clean(); throw $e; } } } else { if ($_template->source->uncompiled) { if ($this->smarty->debugging) { Smarty_Internal_Debug::start_render($_template); } try { ob_start(); $_template->source->renderUncompiled($_template); } catch (Exception $e) { ob_get_clean(); throw $e; } } else { throw new SmartyException("Resource '$_template->source->type' must have 'renderUncompiled' method"); } } $_output = ob_get_clean(); if (!$_template->source->recompiled && empty($_template->properties['file_dependency'][$_template->source->uid])) { $_template->properties['file_dependency'][$_template->source->uid] = array($_template->source->filepath, $_template->source->timestamp, $_template->source->type); } if ($_template->parent instanceof Smarty_Internal_Template) { $_template->parent->properties['file_dependency'] = array_merge($_template->parent->properties['file_dependency'], $_template->properties['file_dependency']); foreach ($_template->required_plugins as $code => $tmp1) { foreach ($tmp1 as $name => $tmp) { foreach ($tmp as $type => $data) { $_template->parent->required_plugins[$code][$name][$type] = $data; } } } } if ($this->smarty->debugging) { Smarty_Internal_Debug::end_render($_template); } // write to cache when nessecary if (!$_template->source->recompiled && ($_template->caching == Smarty::CACHING_LIFETIME_SAVED || $_template->caching == Smarty::CACHING_LIFETIME_CURRENT)) { if ($this->smarty->debugging) { Smarty_Internal_Debug::start_cache($_template); } $_template->properties['has_nocache_code'] = false; // get text between non-cached items $cache_split = preg_split("!/\*%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*\/(.+?)/\*/%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!s", $_output); // get non-cached items preg_match_all("!/\*%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*\/(.+?)/\*/%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!s", $_output, $cache_parts); $output = ''; // loop over items, stitch back together foreach ($cache_split as $curr_idx => $curr_split) { // escape PHP tags in template content $output .= preg_replace('/(<%|%>|<\?php|<\?|\?>)/', '<?php echo \'$1\'; ?>', $curr_split); if (isset($cache_parts[0][$curr_idx])) { $_template->properties['has_nocache_code'] = true; // remove nocache tags from cache output $output .= preg_replace("!/\*/?%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!", '', $cache_parts[0][$curr_idx]); } } if (!$no_output_filter && (isset($this->smarty->autoload_filters['output']) || isset($this->smarty->registered_filters['output']))) { $output = Smarty_Internal_Filter_Handler::runFilter('output', $output, $_template); } // rendering (must be done before writing cache file because of {function} nocache handling) $_smarty_tpl = $_template; try { ob_start(); eval("?>" . $output); $_output = ob_get_clean(); } catch (Exception $e) { ob_get_clean(); throw $e; } // write cache file content $_template->writeCachedContent($output); if ($this->smarty->debugging) { Smarty_Internal_Debug::end_cache($_template); } } else { // var_dump('renderTemplate', $_template->has_nocache_code, $_template->template_resource, $_template->properties['nocache_hash'], $_template->parent->properties['nocache_hash'], $_output); if (!empty($_template->properties['nocache_hash']) && !empty($_template->parent->properties['nocache_hash'])) { // replace nocache_hash $_output = preg_replace("/{$_template->properties['nocache_hash']}/", $_template->parent->properties['nocache_hash'], $_output); $_template->parent->has_nocache_code = $_template->parent->has_nocache_code || $_template->has_nocache_code; } } } else { if ($this->smarty->debugging) { Smarty_Internal_Debug::start_cache($_template); } try { ob_start(); array_unshift($_template->_capture_stack,array()); // // render cached template // $_template->properties['unifunc']($_template); // any unclosed {capture} tags ? if (isset($_template->_capture_stack[0][0])) { $_template->capture_error(); } array_shift($_template->_capture_stack); $_output = ob_get_clean(); } catch (Exception $e) { ob_get_clean(); throw $e; } if ($this->smarty->debugging) { Smarty_Internal_Debug::end_cache($_template); } } if ((!$this->caching || $_template->source->recompiled) && !$no_output_filter && (isset($this->smarty->autoload_filters['output']) || isset($this->smarty->registered_filters['output']))) { $_output = Smarty_Internal_Filter_Handler::runFilter('output', $_output, $_template); } if (isset($this->error_reporting)) { error_reporting($_smarty_old_error_level); } // display or fetch if ($display) { if ($this->caching && $this->cache_modified_check) { $_isCached = $_template->isCached() && !$_template->has_nocache_code; $_last_modified_date = @substr($_SERVER['HTTP_IF_MODIFIED_SINCE'], 0, strpos($_SERVER['HTTP_IF_MODIFIED_SINCE'], 'GMT') + 3); if ($_isCached && $_template->cached->timestamp <= strtotime($_last_modified_date)) { switch (PHP_SAPI) { case 'cgi': // php-cgi < 5.3 case 'cgi-fcgi': // php-cgi >= 5.3 case 'fpm-fcgi': // php-fpm >= 5.3.3 header('Status: 304 Not Modified'); break; case 'cli': if (/* ^phpunit */!empty($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS'])/* phpunit$ */) { $_SERVER['SMARTY_PHPUNIT_HEADERS'][] = '304 Not Modified'; } break; default: header('HTTP/1.1 304 Not Modified'); break; } } else { switch (PHP_SAPI) { case 'cli': if (/* ^phpunit */!empty($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS'])/* phpunit$ */) { $_SERVER['SMARTY_PHPUNIT_HEADERS'][] = 'Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->cached->timestamp) . ' GMT'; } break; default: header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->cached->timestamp) . ' GMT'); break; } echo $_output; } } else { echo $_output; } // debug output if ($this->smarty->debugging) { Smarty_Internal_Debug::display_debug($this); } if ($merge_tpl_vars) { // restore local variables $_template->tpl_vars = $save_tpl_vars; $_template->config_vars = $save_config_vars; } return; } else { if ($merge_tpl_vars) { // restore local variables $_template->tpl_vars = $save_tpl_vars; $_template->config_vars = $save_config_vars; } // return fetched content return $_output; } } /** * displays a Smarty template * * @param string $template the resource handle of the template file or template object * @param mixed $cache_id cache id to be used with this template * @param mixed $compile_id compile id to be used with this template * @param object $parent next higher level of Smarty variables */ public function display($template = null, $cache_id = null, $compile_id = null, $parent = null) { // display template $this->fetch($template, $cache_id, $compile_id, $parent, true); } /** * test if cache is valid * * @param string|object $template the resource handle of the template file or template object * @param mixed $cache_id cache id to be used with this template * @param mixed $compile_id compile id to be used with this template * @param object $parent next higher level of Smarty variables * @return boolean cache status */ public function isCached($template = null, $cache_id = null, $compile_id = null, $parent = null) { if ($template === null && $this instanceof $this->template_class) { return $this->cached->valid; } if (!($template instanceof $this->template_class)) { if ($parent === null) { $parent = $this; } $template = $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false); } // return cache status of template return $template->cached->valid; } /** * creates a data object * * @param object $parent next higher level of Smarty variables * @returns Smarty_Data data object */ public function createData($parent = null) { return new Smarty_Data($parent, $this); } /** * Registers plugin to be used in templates * * @param string $type plugin type * @param string $tag name of template tag * @param callback $callback PHP callback to register * @param boolean $cacheable if true (default) this fuction is cachable * @param array $cache_attr caching attributes if any * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining * @throws SmartyException when the plugin tag is invalid */ public function registerPlugin($type, $tag, $callback, $cacheable = true, $cache_attr = null) { if (isset($this->smarty->registered_plugins[$type][$tag])) { throw new SmartyException("Plugin tag \"{$tag}\" already registered"); } elseif (!is_callable($callback)) { throw new SmartyException("Plugin \"{$tag}\" not callable"); } else { $this->smarty->registered_plugins[$type][$tag] = array($callback, (bool) $cacheable, (array) $cache_attr); } return $this; } /** * Unregister Plugin * * @param string $type of plugin * @param string $tag name of plugin * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining */ public function unregisterPlugin($type, $tag) { if (isset($this->smarty->registered_plugins[$type][$tag])) { unset($this->smarty->registered_plugins[$type][$tag]); } return $this; } /** * Registers a resource to fetch a template * * @param string $type name of resource type * @param Smarty_Resource|array $callback or instance of Smarty_Resource, or array of callbacks to handle resource (deprecated) * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining */ public function registerResource($type, $callback) { $this->smarty->registered_resources[$type] = $callback instanceof Smarty_Resource ? $callback : array($callback, false); return $this; } /** * Unregisters a resource * * @param string $type name of resource type * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining */ public function unregisterResource($type) { if (isset($this->smarty->registered_resources[$type])) { unset($this->smarty->registered_resources[$type]); } return $this; } /** * Registers a cache resource to cache a template's output * * @param string $type name of cache resource type * @param Smarty_CacheResource $callback instance of Smarty_CacheResource to handle output caching * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining */ public function registerCacheResource($type, Smarty_CacheResource $callback) { $this->smarty->registered_cache_resources[$type] = $callback; return $this; } /** * Unregisters a cache resource * * @param string $type name of cache resource type * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining */ public function unregisterCacheResource($type) { if (isset($this->smarty->registered_cache_resources[$type])) { unset($this->smarty->registered_cache_resources[$type]); } return $this; } /** * 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 array $allowed list of allowed methods (empty = all) * @param boolean $smarty_args smarty argument format, else traditional * @param array $block_methods list of block-methods * @param array $block_functs list of methods that are block format * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining * @throws SmartyException if any of the methods in $allowed or $block_methods are invalid */ public function registerObject($object_name, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array()) { // test if allowed methodes callable if (!empty($allowed)) { foreach ((array) $allowed as $method) { if (!is_callable(array($object_impl, $method))) { throw new SmartyException("Undefined method '$method' in registered object"); } } } // test if block methodes callable if (!empty($block_methods)) { foreach ((array) $block_methods as $method) { if (!is_callable(array($object_impl, $method))) { throw new SmartyException("Undefined method '$method' in registered object"); } } } // register the object $this->smarty->registered_objects[$object_name] = array($object_impl, (array) $allowed, (boolean) $smarty_args, (array) $block_methods); return $this; } /** * return a reference to a registered object * * @param string $name object name * @return object * @throws SmartyException if no such object is found */ public function getRegisteredObject($name) { if (!isset($this->smarty->registered_objects[$name])) { throw new SmartyException("'$name' is not a registered object"); } if (!is_object($this->smarty->registered_objects[$name][0])) { throw new SmartyException("registered '$name' is not an object"); } return $this->smarty->registered_objects[$name][0]; } /** * unregister an object * * @param string $name object name * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining */ public function unregisterObject($name) { if (isset($this->smarty->registered_objects[$name])) { unset($this->smarty->registered_objects[$name]); } return $this; } /** * Registers static classes to be used in templates * * @param string $class name of template class * @param string $class_impl the referenced PHP class to register * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining * @throws SmartyException if $class_impl does not refer to an existing class */ public function registerClass($class_name, $class_impl) { // test if exists if (!class_exists($class_impl)) { throw new SmartyException("Undefined class '$class_impl' in register template class"); } // register the class $this->smarty->registered_classes[$class_name] = $class_impl; return $this; } /** * Registers a default plugin handler * * @param callable $callback class/method name * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining * @throws SmartyException if $callback is not callable */ public function registerDefaultPluginHandler($callback) { if (is_callable($callback)) { $this->smarty->default_plugin_handler_func = $callback; } else { throw new SmartyException("Default plugin handler '$callback' not callable"); } return $this; } /** * Registers a default template handler * * @param callable $callback class/method name * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining * @throws SmartyException if $callback is not callable */ public function registerDefaultTemplateHandler($callback) { if (is_callable($callback)) { $this->smarty->default_template_handler_func = $callback; } else { throw new SmartyException("Default template handler '$callback' not callable"); } return $this; } /** * Registers a default template handler * * @param callable $callback class/method name * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining * @throws SmartyException if $callback is not callable */ public function registerDefaultConfigHandler($callback) { if (is_callable($callback)) { $this->smarty->default_config_handler_func = $callback; } else { throw new SmartyException("Default config handler '$callback' not callable"); } return $this; } /** * Registers a filter function * * @param string $type filter type * @param callback $callback * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining */ public function registerFilter($type, $callback) { $this->smarty->registered_filters[$type][$this->_get_filter_name($callback)] = $callback; return $this; } /** * Unregisters a filter function * * @param string $type filter type * @param callback $callback * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining */ public function unregisterFilter($type, $callback) { $name = $this->_get_filter_name($callback); if (isset($this->smarty->registered_filters[$type][$name])) { unset($this->smarty->registered_filters[$type][$name]); } return $this; } /** * Return internal filter name * * @param callback $function_name * @return string internal filter name */ public function _get_filter_name($function_name) { if (is_array($function_name)) { $_class_name = (is_object($function_name[0]) ? get_class($function_name[0]) : $function_name[0]); return $_class_name . '_' . $function_name[1]; } else { return $function_name; } } /** * load a filter of specified type and name * * @param string $type filter type * @param string $name filter name * @throws SmartyException if filter could not be loaded */ public function loadFilter($type, $name) { $_plugin = "smarty_{$type}filter_{$name}"; $_filter_name = $_plugin; if ($this->smarty->loadPlugin($_plugin)) { if (class_exists($_plugin, false)) { $_plugin = array($_plugin, 'execute'); } if (is_callable($_plugin)) { $this->smarty->registered_filters[$type][$_filter_name] = $_plugin; return true; } } throw new SmartyException("{$type}filter \"{$name}\" not callable"); } /** * unload a filter of specified type and name * * @param string $type filter type * @param string $name filter name * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining */ public function unloadFilter($type, $name) { $_filter_name = "smarty_{$type}filter_{$name}"; if (isset($this->smarty->registered_filters[$type][$_filter_name])) { unset ($this->smarty->registered_filters[$type][$_filter_name]); } return $this; } /** * preg_replace callback to convert camelcase getter/setter to underscore property names * * @param string $match match string * @return string replacemant */ private function replaceCamelcase($match) { return "_" . strtolower($match[1]); } /** * Handle unknown class methods * * @param string $name unknown method-name * @param array $args argument array */ public function __call($name, $args) { static $_prefixes = array('set' => true, 'get' => true); static $_resolved_property_name = array(); static $_resolved_property_source = array(); // method of Smarty object? if (method_exists($this->smarty, $name)) { return call_user_func_array(array($this->smarty, $name), $args); } // see if this is a set/get for a property $first3 = strtolower(substr($name, 0, 3)); if (isset($_prefixes[$first3]) && isset($name[3]) && $name[3] !== '_') { if (isset($_resolved_property_name[$name])) { $property_name = $_resolved_property_name[$name]; } else { // try to keep case correct for future PHP 6.0 case-sensitive class methods // lcfirst() not available < PHP 5.3.0, so improvise $property_name = strtolower(substr($name, 3, 1)) . substr($name, 4); // convert camel case to underscored name $property_name = preg_replace_callback('/([A-Z])/', array($this,'replaceCamelcase'), $property_name); $_resolved_property_name[$name] = $property_name; } if (isset($_resolved_property_source[$property_name])) { $_is_this = $_resolved_property_source[$property_name]; } else { $_is_this = null; if (property_exists($this, $property_name)) { $_is_this = true; } else if (property_exists($this->smarty, $property_name)) { $_is_this = false; } $_resolved_property_source[$property_name] = $_is_this; } if ($_is_this) { if ($first3 == 'get') return $this->$property_name; else return $this->$property_name = $args[0]; } else if ($_is_this === false) { if ($first3 == 'get') return $this->smarty->$property_name; else return $this->smarty->$property_name = $args[0]; } else { throw new SmartyException("property '$property_name' does not exist."); return false; } } if ($name == 'Smarty') { throw new SmartyException("PHP5 requires you to call __construct() instead of Smarty()"); } // must be unknown throw new SmartyException("Call of unknown method '$name'."); } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_internal_templatebase.php
PHP
asf20
35,754
<?php /** * Smarty Internal Plugin Resource Stream * * Implements the streams as resource for Smarty template * * @package Smarty * @subpackage TemplateResources * @author Uwe Tews * @author Rodney Rehm */ /** * Smarty Internal Plugin Resource Stream * * Implements the streams as resource for Smarty template * * @link http://php.net/streams * @package Smarty * @subpackage TemplateResources */ class Smarty_Internal_Resource_Stream extends Smarty_Resource_Recompiled { /** * populate Source Object with meta data from Resource * * @param Smarty_Template_Source $source source object * @param Smarty_Internal_Template $_template template object * @return void */ public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template=null) { $source->filepath = str_replace(':', '://', $source->resource); $source->uid = false; $source->content = $this->getContent($source); $source->timestamp = false; $source->exists = !!$source->content; } /** * Load template's source from stream into current template object * * @param Smarty_Template_Source $source source object * @return string template source * @throws SmartyException if source cannot be loaded */ public function getContent(Smarty_Template_Source $source) { $t = ''; // the availability of the stream has already been checked in Smarty_Resource::fetch() $fp = fopen($source->filepath, 'r+'); if ($fp) { while (!feof($fp) && ($current_line = fgets($fp)) !== false) { $t .= $current_line; } fclose($fp); return $t; } else { return false; } } /** * modify resource_name according to resource handlers specifications * * @param Smarty $smarty Smarty instance * @param string $resource_name resource_name to make unique * @return string unique resource name */ protected function buildUniqueResourceName(Smarty $smarty, $resource_name) { return get_class($this) . '#' . $resource_name; } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_internal_resource_stream.php
PHP
asf20
2,294
<?php /** * Smarty Internal Plugin Compile Eval * * Compiles the {eval} tag. * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Eval Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Eval extends Smarty_Internal_CompileBase { /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $required_attributes = array('var'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $optional_attributes = array('assign'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $shorttag_order = array('var','assign'); /** * Compiles code for the {eval} tag * * @param array $args array with attributes from parser * @param object $compiler compiler object * @return string compiled code */ public function compile($args, $compiler) { $this->required_attributes = array('var'); $this->optional_attributes = array('assign'); // check and get attributes $_attr = $this->getAttributes($compiler, $args); if (isset($_attr['assign'])) { // output will be stored in a smarty variable instead of beind displayed $_assign = $_attr['assign']; } // create template object $_output = "\$_template = new {$compiler->smarty->template_class}('eval:'.".$_attr['var'].", \$_smarty_tpl->smarty, \$_smarty_tpl);"; //was there an assign attribute? if (isset($_assign)) { $_output .= "\$_smarty_tpl->assign($_assign,\$_template->fetch());"; } else { $_output .= "echo \$_template->fetch();"; } return "<?php $_output ?>"; } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_internal_compile_eval.php
PHP
asf20
2,044
<?php /** * Smarty Resource Plugin * * @package Smarty * @subpackage TemplateResources * @author Rodney Rehm */ /** * Smarty Resource Plugin * * Base implementation for resource plugins * * @package Smarty * @subpackage TemplateResources */ abstract class Smarty_Resource { /** * cache for Smarty_Template_Source instances * @var array */ public static $sources = array(); /** * cache for Smarty_Template_Compiled instances * @var array */ public static $compileds = array(); /** * cache for Smarty_Resource instances * @var array */ public static $resources = array(); /** * resource types provided by the core * @var array */ protected static $sysplugins = array( 'file' => true, 'string' => true, 'extends' => true, 'stream' => true, 'eval' => true, 'php' => true ); /** * Name of the Class to compile this resource's contents with * @var string */ public $compiler_class = 'Smarty_Internal_SmartyTemplateCompiler'; /** * Name of the Class to tokenize this resource's contents with * @var string */ public $template_lexer_class = 'Smarty_Internal_Templatelexer'; /** * Name of the Class to parse this resource's contents with * @var string */ public $template_parser_class = 'Smarty_Internal_Templateparser'; /** * Load template's source into current template object * * {@internal The loaded source is assigned to $_template->source->content directly.}} * * @param Smarty_Template_Source $source source object * @return string template source * @throws SmartyException if source cannot be loaded */ public abstract function getContent(Smarty_Template_Source $source); /** * populate Source Object with meta data from Resource * * @param Smarty_Template_Source $source source object * @param Smarty_Internal_Template $_template template object */ public abstract function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template=null); /** * populate Source Object with timestamp and exists from Resource * * @param Smarty_Template_Source $source source object */ public function populateTimestamp(Smarty_Template_Source $source) { // intentionally left blank } /** * modify resource_name according to resource handlers specifications * * @param Smarty $smarty Smarty instance * @param string $resource_name resource_name to make unique * @return string unique resource name */ protected function buildUniqueResourceName(Smarty $smarty, $resource_name) { return get_class($this) . '#' . $smarty->joined_template_dir . '#' . $resource_name; } /** * populate Compiled Object with compiled filepath * * @param Smarty_Template_Compiled $compiled compiled object * @param Smarty_Internal_Template $_template template object */ public function populateCompiledFilepath(Smarty_Template_Compiled $compiled, Smarty_Internal_Template $_template) { $_compile_id = isset($_template->compile_id) ? preg_replace('![^\w\|]+!', '_', $_template->compile_id) : null; $_filepath = $compiled->source->uid; // if use_sub_dirs, break file into directories if ($_template->smarty->use_sub_dirs) { $_filepath = substr($_filepath, 0, 2) . DS . substr($_filepath, 2, 2) . DS . substr($_filepath, 4, 2) . DS . $_filepath; } $_compile_dir_sep = $_template->smarty->use_sub_dirs ? DS : '^'; if (isset($_compile_id)) { $_filepath = $_compile_id . $_compile_dir_sep . $_filepath; } // caching token if ($_template->caching) { $_cache = '.cache'; } else { $_cache = ''; } $_compile_dir = $_template->smarty->getCompileDir(); // set basename if not specified $_basename = $this->getBasename($compiled->source); if ($_basename === null) { $_basename = basename( preg_replace('![^\w\/]+!', '_', $compiled->source->name) ); } // separate (optional) basename by dot if ($_basename) { $_basename = '.' . $_basename; } $compiled->filepath = $_compile_dir . $_filepath . '.' . $compiled->source->type . $_basename . $_cache . '.php'; } /** * build template filepath by traversing the template_dir array * * @param Smarty_Template_Source $source source object * @param Smarty_Internal_Template $_template template object * @return string fully qualified filepath * @throws SmartyException if default template handler is registered but not callable */ protected function buildFilepath(Smarty_Template_Source $source, Smarty_Internal_Template $_template=null) { $file = $source->name; if ($source instanceof Smarty_Config_Source) { $_directories = $source->smarty->getConfigDir(); $_default_handler = $source->smarty->default_config_handler_func; } else { $_directories = $source->smarty->getTemplateDir(); $_default_handler = $source->smarty->default_template_handler_func; } // go relative to a given template? $_file_is_dotted = $file[0] == '.' && ($file[1] == '.' || $file[1] == '/' || $file[1] == "\\"); if ($_template && $_template->parent instanceof Smarty_Internal_Template && $_file_is_dotted) { if ($_template->parent->source->type != 'file' && $_template->parent->source->type != 'extends' && !$_template->parent->allow_relative_path) { throw new SmartyException("Template '{$file}' cannot be relative to template of resource type '{$_template->parent->source->type}'"); } $file = dirname($_template->parent->source->filepath) . DS . $file; $_file_exact_match = true; if (!preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $file)) { // the path gained from the parent template is relative to the current working directory // as expansions (like include_path) have already been done $file = getcwd() . DS . $file; } } // resolve relative path if (!preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $file)) { $_was_relative_prefix = $file[0] == '.' ? substr($file, 0, strpos($file, '|')) : null; $_path = DS . trim($file, '/\\'); $_was_relative = true; } else { $_path = $file; } // don't we all just love windows? $_path = str_replace('\\', '/', $_path); // resolve simples $_path = preg_replace('#(/\./(\./)*)|/{2,}#', '/', $_path); // resolve parents while (true) { $_parent = strpos($_path, '/../'); if ($_parent === false) { break; } else if ($_parent === 0) { $_path = substr($_path, 3); break; } $_pos = strrpos($_path, '/', $_parent - strlen($_path) - 1); if ($_pos === false) { // don't we all just love windows? $_pos = $_parent; } $_path = substr_replace($_path, '', $_pos, $_parent + 3 - $_pos); } if (DS != '/') { // don't we all just love windows? $_path = str_replace('/', '\\', $_path); } // revert to relative if (isset($_was_relative)) { if (isset($_was_relative_prefix)){ $_path = $_was_relative_prefix . $_path; } else { $_path = substr($_path, 1); } } // this is only required for directories $file = rtrim($_path, '/\\'); // files relative to a template only get one shot if (isset($_file_exact_match)) { return $this->fileExists($source, $file) ? $file : false; } // template_dir index? if (preg_match('#^\[(?P<key>[^\]]+)\](?P<file>.+)$#', $file, $match)) { $_directory = null; // try string indexes if (isset($_directories[$match['key']])) { $_directory = $_directories[$match['key']]; } else if (is_numeric($match['key'])) { // try numeric index $match['key'] = (int) $match['key']; if (isset($_directories[$match['key']])) { $_directory = $_directories[$match['key']]; } else { // try at location index $keys = array_keys($_directories); $_directory = $_directories[$keys[$match['key']]]; } } if ($_directory) { $_file = substr($file, strpos($file, ']') + 1); $_filepath = $_directory . $_file; if ($this->fileExists($source, $_filepath)) { return $_filepath; } } } // relative file name? if (!preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $file)) { foreach ($_directories as $_directory) { $_filepath = $_directory . $file; if ($this->fileExists($source, $_filepath)) { return $_filepath; } if ($source->smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_directory)) { // try PHP include_path if (($_filepath = Smarty_Internal_Get_Include_Path::getIncludePath($_filepath)) !== false) { if ($this->fileExists($source, $_filepath)) { return $_filepath; } } } } } // try absolute filepath if ($this->fileExists($source, $file)) { return $file; } // no tpl file found if ($_default_handler) { if (!is_callable($_default_handler)) { if ($source instanceof Smarty_Config_Source) { throw new SmartyException("Default config handler not callable"); } else { throw new SmartyException("Default template handler not callable"); } } $_return = call_user_func_array($_default_handler, array($source->type, $source->name, &$_content, &$_timestamp, $source->smarty)); if (is_string($_return)) { $source->timestamp = @filemtime($_return); $source->exists = !!$source->timestamp; return $_return; } elseif ($_return === true) { $source->content = $_content; $source->timestamp = $_timestamp; $source->exists = true; return $_filepath; } } // give up return false; } /** * test is file exists and save timestamp * * @param Smarty_Template_Source $source source object * @param string $file file name * @return bool true if file exists */ protected function fileExists(Smarty_Template_Source $source, $file) { $source->timestamp = @filemtime($file); return $source->exists = !!$source->timestamp; } /** * Determine basename for compiled filename * * @param Smarty_Template_Source $source source object * @return string resource's basename */ protected function getBasename(Smarty_Template_Source $source) { return null; } /** * Load Resource Handler * * @param Smarty $smarty smarty object * @param string $type name of the resource * @return Smarty_Resource Resource Handler */ public static function load(Smarty $smarty, $type) { // try smarty's cache if (isset($smarty->_resource_handlers[$type])) { return $smarty->_resource_handlers[$type]; } // try registered resource if (isset($smarty->registered_resources[$type])) { if ($smarty->registered_resources[$type] instanceof Smarty_Resource) { $smarty->_resource_handlers[$type] = $smarty->registered_resources[$type]; // note registered to smarty is not kept unique! return $smarty->_resource_handlers[$type]; } if (!isset(self::$resources['registered'])) { self::$resources['registered'] = new Smarty_Internal_Resource_Registered(); } if (!isset($smarty->_resource_handlers[$type])) { $smarty->_resource_handlers[$type] = self::$resources['registered']; } return $smarty->_resource_handlers[$type]; } // try sysplugins dir if (isset(self::$sysplugins[$type])) { if (!isset(self::$resources[$type])) { $_resource_class = 'Smarty_Internal_Resource_' . ucfirst($type); self::$resources[$type] = new $_resource_class(); } return $smarty->_resource_handlers[$type] = self::$resources[$type]; } // try plugins dir $_resource_class = 'Smarty_Resource_' . ucfirst($type); if ($smarty->loadPlugin($_resource_class)) { if (isset(self::$resources[$type])) { return $smarty->_resource_handlers[$type] = self::$resources[$type]; } if (class_exists($_resource_class, false)) { self::$resources[$type] = new $_resource_class(); return $smarty->_resource_handlers[$type] = self::$resources[$type]; } else { $smarty->registerResource($type, array( "smarty_resource_{$type}_source", "smarty_resource_{$type}_timestamp", "smarty_resource_{$type}_secure", "smarty_resource_{$type}_trusted" )); // give it another try, now that the resource is registered properly return self::load($smarty, $type); } } // try streams $_known_stream = stream_get_wrappers(); if (in_array($type, $_known_stream)) { // is known stream if (is_object($smarty->security_policy)) { $smarty->security_policy->isTrustedStream($type); } if (!isset(self::$resources['stream'])) { self::$resources['stream'] = new Smarty_Internal_Resource_Stream(); } return $smarty->_resource_handlers[$type] = self::$resources['stream']; } // TODO: try default_(template|config)_handler // give up throw new SmartyException("Unkown resource type '{$type}'"); } /** * extract resource_type and resource_name from template_resource and config_resource * * @note "C:/foo.tpl" was forced to file resource up till Smarty 3.1.3 (including). * @param string $resource_name template_resource or config_resource to parse * @param string $default_resource the default resource_type defined in $smarty * @param string &$name the parsed resource name * @param string &$type the parsed resource type * @return void */ protected static function parseResourceName($resource_name, $default_resource, &$name, &$type) { $parts = explode(':', $resource_name, 2); if (!isset($parts[1]) || !isset($parts[0][1])) { // no resource given, use default // or single character before the colon is not a resource type, but part of the filepath $type = $default_resource; $name = $resource_name; } else { $type = $parts[0]; $name = $parts[1]; } } /** * modify resource_name according to resource handlers specifications * * @param Smarty $smarty Smarty instance * @param string $resource_name resource_name to make unique * @return string unique resource name */ /** * modify template_resource according to resource handlers specifications * * @param string $smarty Smarty instance * @param string $template_resource template_resource to extracate resource handler and name of * @return string unique resource name */ public static function getUniqueTemplateName($smarty, $template_resource) { self::parseResourceName($template_resource, $smarty->default_resource_type, $name, $type); // TODO: optimize for Smarty's internal resource types $resource = Smarty_Resource::load($smarty, $type); return $resource->buildUniqueResourceName($smarty, $name); } /** * initialize Source Object for given resource * * Either [$_template] or [$smarty, $template_resource] must be specified * * @param Smarty_Internal_Template $_template template object * @param Smarty $smarty smarty object * @param string $template_resource resource identifier * @return Smarty_Template_Source Source Object */ public static function source(Smarty_Internal_Template $_template=null, Smarty $smarty=null, $template_resource=null) { if ($_template) { $smarty = $_template->smarty; $template_resource = $_template->template_resource; } // parse resource_name, load resource handler, identify unique resource name self::parseResourceName($template_resource, $smarty->default_resource_type, $name, $type); $resource = Smarty_Resource::load($smarty, $type); $unique_resource_name = $resource->buildUniqueResourceName($smarty, $name); // check runtime cache $_cache_key = 'template|' . $unique_resource_name; if (isset(self::$sources[$_cache_key])) { return self::$sources[$_cache_key]; } // create source $source = new Smarty_Template_Source($resource, $smarty, $template_resource, $type, $name, $unique_resource_name); $resource->populate($source, $_template); // runtime cache self::$sources[$_cache_key] = $source; return $source; } /** * initialize Config Source Object for given resource * * @param Smarty_Internal_Config $_config config object * @return Smarty_Config_Source Source Object */ public static function config(Smarty_Internal_Config $_config) { static $_incompatible_resources = array('eval' => true, 'string' => true, 'extends' => true, 'php' => true); $config_resource = $_config->config_resource; $smarty = $_config->smarty; // parse resource_name self::parseResourceName($config_resource, $smarty->default_config_type, $name, $type); // make sure configs are not loaded via anything smarty can't handle if (isset($_incompatible_resources[$type])) { throw new SmartyException ("Unable to use resource '{$type}' for config"); } // load resource handler, identify unique resource name $resource = Smarty_Resource::load($smarty, $type); $unique_resource_name = $resource->buildUniqueResourceName($smarty, $name); // check runtime cache $_cache_key = 'config|' . $unique_resource_name; if (isset(self::$sources[$_cache_key])) { return self::$sources[$_cache_key]; } // create source $source = new Smarty_Config_Source($resource, $smarty, $config_resource, $type, $name, $unique_resource_name); $resource->populate($source, null); // runtime cache self::$sources[$_cache_key] = $source; return $source; } } /** * Smarty Resource Data Object * * Meta Data Container for Template Files * * @package Smarty * @subpackage TemplateResources * @author Rodney Rehm * * @property integer $timestamp Source Timestamp * @property boolean $exists Source Existance * @property boolean $template Extended Template reference * @property string $content Source Content */ class Smarty_Template_Source { /** * Name of the Class to compile this resource's contents with * @var string */ public $compiler_class = null; /** * Name of the Class to tokenize this resource's contents with * @var string */ public $template_lexer_class = null; /** * Name of the Class to parse this resource's contents with * @var string */ public $template_parser_class = null; /** * Unique Template ID * @var string */ public $uid = null; /** * Template Resource (Smarty_Internal_Template::$template_resource) * @var string */ public $resource = null; /** * Resource Type * @var string */ public $type = null; /** * Resource Name * @var string */ public $name = null; /** * Unique Resource Name * @var string */ public $unique_resource = null; /** * Source Filepath * @var string */ public $filepath = null; /** * Source is bypassing compiler * @var boolean */ public $uncompiled = null; /** * Source must be recompiled on every occasion * @var boolean */ public $recompiled = null; /** * The Components an extended template is made of * @var array */ public $components = null; /** * Resource Handler * @var Smarty_Resource */ public $handler = null; /** * Smarty instance * @var Smarty */ public $smarty = null; /** * create Source Object container * * @param Smarty_Resource $handler Resource Handler this source object communicates with * @param Smarty $smarty Smarty instance this source object belongs to * @param string $resource full template_resource * @param string $type type of resource * @param string $name resource name * @param string $unique_resource unqiue resource name */ public function __construct(Smarty_Resource $handler, Smarty $smarty, $resource, $type, $name, $unique_resource) { $this->handler = $handler; // Note: prone to circular references $this->compiler_class = $handler->compiler_class; $this->template_lexer_class = $handler->template_lexer_class; $this->template_parser_class = $handler->template_parser_class; $this->uncompiled = $this->handler instanceof Smarty_Resource_Uncompiled; $this->recompiled = $this->handler instanceof Smarty_Resource_Recompiled; $this->smarty = $smarty; $this->resource = $resource; $this->type = $type; $this->name = $name; $this->unique_resource = $unique_resource; } /** * get a Compiled Object of this source * * @param Smarty_Internal_Template $_template template objet * @return Smarty_Template_Compiled compiled object */ public function getCompiled(Smarty_Internal_Template $_template) { // check runtime cache $_cache_key = $this->unique_resource . '#' . $_template->compile_id; if (isset(Smarty_Resource::$compileds[$_cache_key])) { return Smarty_Resource::$compileds[$_cache_key]; } $compiled = new Smarty_Template_Compiled($this); $this->handler->populateCompiledFilepath($compiled, $_template); $compiled->timestamp = @filemtime($compiled->filepath); $compiled->exists = !!$compiled->timestamp; // runtime cache Smarty_Resource::$compileds[$_cache_key] = $compiled; return $compiled; } /** * render the uncompiled source * * @param Smarty_Internal_Template $_template template object */ public function renderUncompiled(Smarty_Internal_Template $_template) { return $this->handler->renderUncompiled($this, $_template); } /** * <<magic>> Generic Setter. * * @param string $property_name valid: timestamp, exists, content, template * @param mixed $value new value (is not checked) * @throws SmartyException if $property_name is not valid */ public function __set($property_name, $value) { switch ($property_name) { // regular attributes case 'timestamp': case 'exists': case 'content': // required for extends: only case 'template': $this->$property_name = $value; break; default: throw new SmartyException("invalid source property '$property_name'."); } } /** * <<magic>> Generic getter. * * @param string $property_name valid: timestamp, exists, content * @return mixed * @throws SmartyException if $property_name is not valid */ public function __get($property_name) { switch ($property_name) { case 'timestamp': case 'exists': $this->handler->populateTimestamp($this); return $this->$property_name; case 'content': return $this->content = $this->handler->getContent($this); default: throw new SmartyException("source property '$property_name' does not exist."); } } } /** * Smarty Resource Data Object * * Meta Data Container for Template Files * * @package Smarty * @subpackage TemplateResources * @author Rodney Rehm * * @property string $content compiled content */ class Smarty_Template_Compiled { /** * Compiled Filepath * @var string */ public $filepath = null; /** * Compiled Timestamp * @var integer */ public $timestamp = null; /** * Compiled Existance * @var boolean */ public $exists = false; /** * Compiled Content Loaded * @var boolean */ public $loaded = false; /** * Template was compiled * @var boolean */ public $isCompiled = false; /** * Source Object * @var Smarty_Template_Source */ public $source = null; /** * Metadata properties * * populated by Smarty_Internal_Template::decodeProperties() * @var array */ public $_properties = null; /** * create Compiled Object container * * @param Smarty_Template_Source $source source object this compiled object belongs to */ public function __construct(Smarty_Template_Source $source) { $this->source = $source; } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_resource.php
PHP
asf20
28,097
<?php /** * Smarty Internal Plugin Compile Nocache * * Compiles the {nocache} {/nocache} tags. * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Nocache Classv * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Nocache extends Smarty_Internal_CompileBase { /** * Compiles code for the {nocache} tag * * This tag does not generate compiled output. It only sets a compiler flag. * * @param array $args array with attributes from parser * @param object $compiler compiler object * @return bool */ public function compile($args, $compiler) { $_attr = $this->getAttributes($compiler, $args); if ($_attr['nocache'] === true) { $compiler->trigger_template_error('nocache option not allowed', $compiler->lex->taglineno); } // enter nocache mode $compiler->nocache = true; // this tag does not return compiled code $compiler->has_code = false; return true; } } /** * Smarty Internal Plugin Compile Nocacheclose Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Nocacheclose extends Smarty_Internal_CompileBase { /** * Compiles code for the {/nocache} tag * * This tag does not generate compiled output. It only sets a compiler flag. * * @param array $args array with attributes from parser * @param object $compiler compiler object * @return bool */ public function compile($args, $compiler) { $_attr = $this->getAttributes($compiler, $args); // leave nocache mode $compiler->nocache = false; // this tag does not return compiled code $compiler->has_code = false; return true; } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_internal_compile_nocache.php
PHP
asf20
1,926
<?php /** * Smarty Internal Plugin * * @package Smarty * @subpackage TemplateResources */ /** * Smarty Resource Data Object * * Meta Data Container for Config Files * * @package Smarty * @subpackage TemplateResources * @author Rodney Rehm * * @property string $content * @property int $timestamp * @property bool $exists */ class Smarty_Config_Source extends Smarty_Template_Source { /** * create Config Object container * * @param Smarty_Resource $handler Resource Handler this source object communicates with * @param Smarty $smarty Smarty instance this source object belongs to * @param string $resource full config_resource * @param string $type type of resource * @param string $name resource name * @param string $unique_resource unqiue resource name */ public function __construct(Smarty_Resource $handler, Smarty $smarty, $resource, $type, $name, $unique_resource) { $this->handler = $handler; // Note: prone to circular references // Note: these may be ->config_compiler_class etc in the future //$this->config_compiler_class = $handler->config_compiler_class; //$this->config_lexer_class = $handler->config_lexer_class; //$this->config_parser_class = $handler->config_parser_class; $this->smarty = $smarty; $this->resource = $resource; $this->type = $type; $this->name = $name; $this->unique_resource = $unique_resource; } /** * <<magic>> Generic setter. * * @param string $property_name valid: content, timestamp, exists * @param mixed $value newly assigned value (not check for correct type) * @throws SmartyException when the given property name is not valid */ public function __set($property_name, $value) { switch ($property_name) { case 'content': case 'timestamp': case 'exists': $this->$property_name = $value; break; default: throw new SmartyException("invalid config property '$property_name'."); } } /** * <<magic>> Generic getter. * * @param string $property_name valid: content, timestamp, exists * @throws SmartyException when the given property name is not valid */ public function __get($property_name) { switch ($property_name) { case 'timestamp': case 'exists': $this->handler->populateTimestamp($this); return $this->$property_name; case 'content': return $this->content = $this->handler->getContent($this); default: throw new SmartyException("config property '$property_name' does not exist."); } } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_config_source.php
PHP
asf20
3,035
<?php /** * Smarty Internal Plugin Template * * This file contains the Smarty template engine * * @package Smarty * @subpackage Template * @author Uwe Tews */ /** * Main class with template data structures and methods * * @package Smarty * @subpackage Template * * @property Smarty_Template_Source $source * @property Smarty_Template_Compiled $compiled * @property Smarty_Template_Cached $cached */ class Smarty_Internal_Template extends Smarty_Internal_TemplateBase { /** * cache_id * @var string */ public $cache_id = null; /** * $compile_id * @var string */ public $compile_id = null; /** * caching enabled * @var boolean */ public $caching = null; /** * cache lifetime in seconds * @var integer */ public $cache_lifetime = null; /** * Template resource * @var string */ public $template_resource = null; /** * flag if compiled template is invalid and must be (re)compiled * @var bool */ public $mustCompile = null; /** * flag if template does contain nocache code sections * @var bool */ public $has_nocache_code = false; /** * special compiled and cached template properties * @var array */ public $properties = array('file_dependency' => array(), 'nocache_hash' => '', 'function' => array()); /** * required plugins * @var array */ public $required_plugins = array('compiled' => array(), 'nocache' => array()); /** * Global smarty instance * @var Smarty */ public $smarty = null; /** * blocks for template inheritance * @var array */ public $block_data = array(); /** * variable filters * @var array */ public $variable_filters = array(); /** * optional log of tag/attributes * @var array */ public $used_tags = array(); /** * internal flag to allow relative path in child template blocks * @var bool */ public $allow_relative_path = false; /** * internal capture runtime stack * @var array */ public $_capture_stack = array(0 => array()); /** * Create template data object * * Some of the global Smarty settings copied to template scope * It load the required template resources and cacher plugins * * @param string $template_resource template resource string * @param Smarty $smarty Smarty instance * @param Smarty_Internal_Template $_parent back pointer to parent object with variables or null * @param mixed $_cache_id cache id or null * @param mixed $_compile_id compile id or null * @param bool $_caching use caching? * @param int $_cache_lifetime cache life-time in seconds */ public function __construct($template_resource, $smarty, $_parent = null, $_cache_id = null, $_compile_id = null, $_caching = null, $_cache_lifetime = null) { $this->smarty = &$smarty; // Smarty parameter $this->cache_id = $_cache_id === null ? $this->smarty->cache_id : $_cache_id; $this->compile_id = $_compile_id === null ? $this->smarty->compile_id : $_compile_id; $this->caching = $_caching === null ? $this->smarty->caching : $_caching; if ($this->caching === true) $this->caching = Smarty::CACHING_LIFETIME_CURRENT; $this->cache_lifetime = $_cache_lifetime === null ? $this->smarty->cache_lifetime : $_cache_lifetime; $this->parent = $_parent; // Template resource $this->template_resource = $template_resource; // copy block data of template inheritance if ($this->parent instanceof Smarty_Internal_Template) { $this->block_data = $this->parent->block_data; } } /** * Returns if the current template must be compiled by the Smarty compiler * * It does compare the timestamps of template source and the compiled templates and checks the force compile configuration * * @return boolean true if the template must be compiled */ public function mustCompile() { if (!$this->source->exists) { if ($this->parent instanceof Smarty_Internal_Template) { $parent_resource = " in '$this->parent->template_resource}'"; } else { $parent_resource = ''; } throw new SmartyException("Unable to load template {$this->source->type} '{$this->source->name}'{$parent_resource}"); } if ($this->mustCompile === null) { $this->mustCompile = (!$this->source->uncompiled && ($this->smarty->force_compile || $this->source->recompiled || $this->compiled->timestamp === false || ($this->smarty->compile_check && $this->compiled->timestamp < $this->source->timestamp))); } return $this->mustCompile; } /** * Compiles the template * * If the template is not evaluated the compiled template is saved on disk */ public function compileTemplateSource() { if (!$this->source->recompiled) { $this->properties['file_dependency'] = array(); if ($this->source->components) { // uses real resource for file dependency $source = end($this->source->components); $this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $source->type); } else { $this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $this->source->type); } } if ($this->smarty->debugging) { Smarty_Internal_Debug::start_compile($this); } // compile locking if ($this->smarty->compile_locking && !$this->source->recompiled) { if ($saved_timestamp = $this->compiled->timestamp) { touch($this->compiled->filepath); } } // call compiler try { $code = $this->compiler->compileTemplate($this); } catch (Exception $e) { // restore old timestamp in case of error if ($this->smarty->compile_locking && !$this->source->recompiled && $saved_timestamp) { touch($this->compiled->filepath, $saved_timestamp); } throw $e; } // compiling succeded if (!$this->source->recompiled && $this->compiler->write_compiled_code) { // write compiled template $_filepath = $this->compiled->filepath; if ($_filepath === false) throw new SmartyException('getCompiledFilepath() did not return a destination to save the compiled template to'); Smarty_Internal_Write_File::writeFile($_filepath, $code, $this->smarty); $this->compiled->exists = true; $this->compiled->isCompiled = true; } if ($this->smarty->debugging) { Smarty_Internal_Debug::end_compile($this); } // release compiler object to free memory unset($this->compiler); } /** * Writes the cached template output * * @return bool */ public function writeCachedContent($content) { if ($this->source->recompiled || !($this->caching == Smarty::CACHING_LIFETIME_CURRENT || $this->caching == Smarty::CACHING_LIFETIME_SAVED)) { // don't write cache file return false; } $this->properties['cache_lifetime'] = $this->cache_lifetime; $this->properties['unifunc'] = 'content_' . uniqid('', false); $content = $this->createTemplateCodeFrame($content, true); $_smarty_tpl = $this; eval("?>" . $content); $this->cached->valid = true; $this->cached->processed = true; return $this->cached->write($this, $content); } /** * Template code runtime function to get subtemplate content * * @param string $template the resource handle of the template file * @param mixed $cache_id cache id to be used with this template * @param mixed $compile_id compile id to be used with this template * @param integer $caching cache mode * @param integer $cache_lifetime life time of cache data * @param array $vars optional variables to assign * @param int $parent_scope scope in which {include} should execute * @returns string template content */ public function getSubTemplate($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $parent_scope) { // already in template cache? if ($this->smarty->allow_ambiguous_resources) { $_templateId = Smarty_Resource::getUniqueTemplateName($this->smarty, $template) . $cache_id . $compile_id; } else { $_templateId = $this->smarty->joined_template_dir . '#' . $template . $cache_id . $compile_id; } if (isset($_templateId[150])) { $_templateId = sha1($_templateId); } if (isset($this->smarty->template_objects[$_templateId])) { // clone cached template object because of possible recursive call $tpl = clone $this->smarty->template_objects[$_templateId]; $tpl->parent = $this; $tpl->caching = $caching; $tpl->cache_lifetime = $cache_lifetime; } else { $tpl = new $this->smarty->template_class($template, $this->smarty, $this, $cache_id, $compile_id, $caching, $cache_lifetime); } // get variables from calling scope if ($parent_scope == Smarty::SCOPE_LOCAL) { $tpl->tpl_vars = $this->tpl_vars; } elseif ($parent_scope == Smarty::SCOPE_PARENT) { $tpl->tpl_vars = &$this->tpl_vars; } elseif ($parent_scope == Smarty::SCOPE_GLOBAL) { $tpl->tpl_vars = &Smarty::$global_tpl_vars; } elseif (($scope_ptr = $this->getScopePointer($parent_scope)) == null) { $tpl->tpl_vars = &$this->tpl_vars; } else { $tpl->tpl_vars = &$scope_ptr->tpl_vars; } $tpl->config_vars = $this->config_vars; if (!empty($data)) { // set up variable values foreach ($data as $_key => $_val) { $tpl->tpl_vars[$_key] = new Smarty_variable($_val); } } return $tpl->fetch(null, null, null, null, false, false, true); } /** * Template code runtime function to set up an inline subtemplate * * @param string $template the resource handle of the template file * @param mixed $cache_id cache id to be used with this template * @param mixed $compile_id compile id to be used with this template * @param integer $caching cache mode * @param integer $cache_lifetime life time of cache data * @param array $vars optional variables to assign * @param int $parent_scope scope in which {include} should execute * @param string $hash nocache hash code * @returns string template content */ public function setupInlineSubTemplate($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $parent_scope, $hash) { $tpl = new $this->smarty->template_class($template, $this->smarty, $this, $cache_id, $compile_id, $caching, $cache_lifetime); $tpl->properties['nocache_hash'] = $hash; // get variables from calling scope if ($parent_scope == Smarty::SCOPE_LOCAL ) { $tpl->tpl_vars = $this->tpl_vars; } elseif ($parent_scope == Smarty::SCOPE_PARENT) { $tpl->tpl_vars = &$this->tpl_vars; } elseif ($parent_scope == Smarty::SCOPE_GLOBAL) { $tpl->tpl_vars = &Smarty::$global_tpl_vars; } elseif (($scope_ptr = $this->getScopePointer($parent_scope)) == null) { $tpl->tpl_vars = &$this->tpl_vars; } else { $tpl->tpl_vars = &$scope_ptr->tpl_vars; } $tpl->config_vars = $this->config_vars; if (!empty($data)) { // set up variable values foreach ($data as $_key => $_val) { $tpl->tpl_vars[$_key] = new Smarty_variable($_val); } } return $tpl; } /** * Create code frame for compiled and cached templates * * @param string $content optional template content * @param bool $cache flag for cache file * @return string */ public function createTemplateCodeFrame($content = '', $cache = false) { $plugins_string = ''; // include code for plugins if (!$cache) { if (!empty($this->required_plugins['compiled'])) { $plugins_string = '<?php '; foreach ($this->required_plugins['compiled'] as $tmp) { foreach ($tmp as $data) { $file = addslashes($data['file']); $plugins_string .= "if (!is_callable('{$data['function']}')) include '{$file}';\n"; } } $plugins_string .= '?>'; } if (!empty($this->required_plugins['nocache'])) { $this->has_nocache_code = true; $plugins_string .= "<?php echo '/*%%SmartyNocache:{$this->properties['nocache_hash']}%%*/<?php \$_smarty = \$_smarty_tpl->smarty; "; foreach ($this->required_plugins['nocache'] as $tmp) { foreach ($tmp as $data) { $file = addslashes($data['file']); $plugins_string .= addslashes("if (!is_callable('{$data['function']}')) include '{$file}';\n"); } } $plugins_string .= "?>/*/%%SmartyNocache:{$this->properties['nocache_hash']}%%*/';?>\n"; } } // build property code $this->properties['has_nocache_code'] = $this->has_nocache_code; $output = ''; if (!$this->source->recompiled) { $output = "<?php /*%%SmartyHeaderCode:{$this->properties['nocache_hash']}%%*/"; if ($this->smarty->direct_access_security) { $output .= "if(!defined('SMARTY_DIR')) exit('no direct access allowed');\n"; } } if ($cache) { // remove compiled code of{function} definition unset($this->properties['function']); if (!empty($this->smarty->template_functions)) { // copy code of {function} tags called in nocache mode foreach ($this->smarty->template_functions as $name => $function_data) { if (isset($function_data['called_nocache'])) { foreach ($function_data['called_functions'] as $func_name) { $this->smarty->template_functions[$func_name]['called_nocache'] = true; } } } foreach ($this->smarty->template_functions as $name => $function_data) { if (isset($function_data['called_nocache'])) { unset($function_data['called_nocache'], $function_data['called_functions'], $this->smarty->template_functions[$name]['called_nocache']); $this->properties['function'][$name] = $function_data; } } } } $this->properties['version'] = Smarty::SMARTY_VERSION; if (!isset($this->properties['unifunc'])) { $this->properties['unifunc'] = 'content_' . uniqid('', false); } if (!$this->source->recompiled) { $output .= "\$_valid = \$_smarty_tpl->decodeProperties(" . var_export($this->properties, true) . ',' . ($cache ? 'true' : 'false') . "); /*/%%SmartyHeaderCode%%*/?>\n"; } if (!$this->source->recompiled) { $output .= '<?php if ($_valid && !is_callable(\'' . $this->properties['unifunc'] . '\')) {function ' . $this->properties['unifunc'] . '($_smarty_tpl) {?>'; } $output .= $plugins_string; $output .= $content; if (!$this->source->recompiled) { $output .= '<?php }} ?>'; } return $output; } /** * This function is executed automatically when a compiled or cached template file is included * * - Decode saved properties from compiled template and cache files * - Check if compiled or cache file is valid * * @param array $properties special template properties * @param bool $cache flag if called from cache file * @return bool flag if compiled or cache file is valid */ public function decodeProperties($properties, $cache = false) { $this->has_nocache_code = $properties['has_nocache_code']; $this->properties['nocache_hash'] = $properties['nocache_hash']; if (isset($properties['cache_lifetime'])) { $this->properties['cache_lifetime'] = $properties['cache_lifetime']; } if (isset($properties['file_dependency'])) { $this->properties['file_dependency'] = array_merge($this->properties['file_dependency'], $properties['file_dependency']); } if (!empty($properties['function'])) { $this->properties['function'] = array_merge($this->properties['function'], $properties['function']); $this->smarty->template_functions = array_merge($this->smarty->template_functions, $properties['function']); } $this->properties['version'] = (isset($properties['version'])) ? $properties['version'] : ''; $this->properties['unifunc'] = $properties['unifunc']; // check file dependencies at compiled code $is_valid = true; if ($this->properties['version'] != Smarty::SMARTY_VERSION) { $is_valid = false; } else if (((!$cache && $this->smarty->compile_check && empty($this->compiled->_properties) && !$this->compiled->isCompiled) || $cache && ($this->smarty->compile_check === true || $this->smarty->compile_check === Smarty::COMPILECHECK_ON)) && !empty($this->properties['file_dependency'])) { foreach ($this->properties['file_dependency'] as $_file_to_check) { if ($_file_to_check[2] == 'file' || $_file_to_check[2] == 'php') { if ($this->source->filepath == $_file_to_check[0] && isset($this->source->timestamp)) { // do not recheck current template $mtime = $this->source->timestamp; } else { // file and php types can be checked without loading the respective resource handlers $mtime = filemtime($_file_to_check[0]); } } elseif ($_file_to_check[2] == 'string') { continue; } else { $source = Smarty_Resource::source(null, $this->smarty, $_file_to_check[0]); $mtime = $source->timestamp; } if ($mtime > $_file_to_check[1]) { $is_valid = false; break; } } } if ($cache) { $this->cached->valid = $is_valid; } else { $this->mustCompile = !$is_valid; } // store data in reusable Smarty_Template_Compiled if (!$cache) { $this->compiled->_properties = $properties; } return $is_valid; } /** * Template code runtime function to create a local Smarty variable for array assignments * * @param string $tpl_var tempate variable name * @param bool $nocache cache mode of variable * @param int $scope scope of variable */ public function createLocalArrayVariable($tpl_var, $nocache = false, $scope = Smarty::SCOPE_LOCAL) { if (!isset($this->tpl_vars[$tpl_var])) { $this->tpl_vars[$tpl_var] = new Smarty_variable(array(), $nocache, $scope); } else { $this->tpl_vars[$tpl_var] = clone $this->tpl_vars[$tpl_var]; if ($scope != Smarty::SCOPE_LOCAL) { $this->tpl_vars[$tpl_var]->scope = $scope; } if (!(is_array($this->tpl_vars[$tpl_var]->value) || $this->tpl_vars[$tpl_var]->value instanceof ArrayAccess)) { settype($this->tpl_vars[$tpl_var]->value, 'array'); } } } /** * Template code runtime function to get pointer to template variable array of requested scope * * @param int $scope requested variable scope * @return array array of template variables */ public function &getScope($scope) { if ($scope == Smarty::SCOPE_PARENT && !empty($this->parent)) { return $this->parent->tpl_vars; } elseif ($scope == Smarty::SCOPE_ROOT && !empty($this->parent)) { $ptr = $this->parent; while (!empty($ptr->parent)) { $ptr = $ptr->parent; } return $ptr->tpl_vars; } elseif ($scope == Smarty::SCOPE_GLOBAL) { return Smarty::$global_tpl_vars; } $null = null; return $null; } /** * Get parent or root of template parent chain * * @param int $scope pqrent or root scope * @return mixed object */ public function getScopePointer($scope) { if ($scope == Smarty::SCOPE_PARENT && !empty($this->parent)) { return $this->parent; } elseif ($scope == Smarty::SCOPE_ROOT && !empty($this->parent)) { $ptr = $this->parent; while (!empty($ptr->parent)) { $ptr = $ptr->parent; } return $ptr; } return null; } /** * [util function] counts an array, arrayaccess/traversable or PDOStatement object * * @param mixed $value * @return int the count for arrays and objects that implement countable, 1 for other objects that don't, and 0 for empty elements */ public function _count($value) { if (is_array($value) === true || $value instanceof Countable) { return count($value); } elseif ($value instanceof IteratorAggregate) { // Note: getIterator() returns a Traversable, not an Iterator // thus rewind() and valid() methods may not be present return iterator_count($value->getIterator()); } elseif ($value instanceof Iterator) { return iterator_count($value); } elseif ($value instanceof PDOStatement) { return $value->rowCount(); } elseif ($value instanceof Traversable) { return iterator_count($value); } elseif ($value instanceof ArrayAccess) { if ($value->offsetExists(0)) { return 1; } } elseif (is_object($value)) { return count($value); } return 0; } /** * runtime error not matching capture tags * */ public function capture_error() { throw new SmartyException("Not matching {capture} open/close in \"{$this->template_resource}\""); } /** * Empty cache for this template * * @param integer $exp_time expiration time * @return integer number of cache files deleted */ public function clearCache($exp_time=null) { Smarty_CacheResource::invalidLoadedCache($this->smarty); return $this->cached->handler->clear($this->smarty, $this->template_name, $this->cache_id, $this->compile_id, $exp_time); } /** * set Smarty property in template context * * @param string $property_name property name * @param mixed $value value */ public function __set($property_name, $value) { switch ($property_name) { case 'source': case 'compiled': case 'cached': case 'compiler': $this->$property_name = $value; return; // FIXME: routing of template -> smarty attributes default: if (property_exists($this->smarty, $property_name)) { $this->smarty->$property_name = $value; return; } } throw new SmartyException("invalid template property '$property_name'."); } /** * get Smarty property in template context * * @param string $property_name property name */ public function __get($property_name) { switch ($property_name) { case 'source': if (empty($this->template_resource)) { throw new SmartyException("Unable to parse resource name \"{$this->template_resource}\""); } $this->source = Smarty_Resource::source($this); // cache template object under a unique ID // do not cache eval resources if ($this->source->type != 'eval') { if ($this->smarty->allow_ambiguous_resources) { $_templateId = $this->source->unique_resource . $this->cache_id . $this->compile_id; } else { $_templateId = $this->smarty->joined_template_dir . '#' . $this->template_resource . $this->cache_id . $this->compile_id; } if (isset($_templateId[150])) { $_templateId = sha1($_templateId); } $this->smarty->template_objects[$_templateId] = $this; } return $this->source; case 'compiled': $this->compiled = $this->source->getCompiled($this); return $this->compiled; case 'cached': if (!class_exists('Smarty_Template_Cached')) { include SMARTY_SYSPLUGINS_DIR . 'smarty_cacheresource.php'; } $this->cached = new Smarty_Template_Cached($this); return $this->cached; case 'compiler': $this->smarty->loadPlugin($this->source->compiler_class); $this->compiler = new $this->source->compiler_class($this->source->template_lexer_class, $this->source->template_parser_class, $this->smarty); return $this->compiler; // FIXME: routing of template -> smarty attributes default: if (property_exists($this->smarty, $property_name)) { return $this->smarty->$property_name; } } throw new SmartyException("template property '$property_name' does not exist."); } /** * Template data object destrutor * */ public function __destruct() { if ($this->smarty->cache_locking && isset($this->cached) && $this->cached->is_locked) { $this->cached->handler->releaseLock($this->smarty, $this->cached); } } } ?>
0x6a
trunk/application/libraries/smarty3/sysplugins/smarty_internal_template.php
PHP
asf20
28,218